From e89b89d71aeb5ba158d33a038ba168be6b84fc64 Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Fri, 20 Nov 2026 19:56:33 -0700 Subject: [PATCH 01/18] gitattributes: mark temporal/api as generated What Marks the generated `temporal/api/` tree as generated in `.gitattributes`. Why GitHub collapses the generated diffs so reviewers can focus on changes to the source schema. Co-Authored-By: Claude Opus 5.5 --- .gitattributes | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..379a8ed21 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# temporal/api is generated from temporal/api_next by make stable-api. +temporal/api/** linguist-generated=true From ed9a2a9e6990a2f8fcd10286feea5ec714068a2b Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Fri, 20 Nov 2026 15:26:36 -0700 Subject: [PATCH 02/18] Makefile: run stable-tree readers after stable-api What Adds `stable-api` as an order-only prerequisite for targets that read `temporal/api/`. Why Parallel builds need the generated schema to be ready before linting, checking compatibility, or generating downstream artifacts. Co-Authored-By: Claude Opus 5.5 --- Makefile | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Makefile b/Makefile index a21bc3f8a..38977b391 100644 --- a/Makefile +++ b/Makefile @@ -59,7 +59,7 @@ stable-api-test: ##### Compile proto files for go ##### grpc: stable-api buf-lint api-linter resource-id-lint buf-breaking clean go-grpc fix-path -go-grpc: clean $(PROTO_OUT) +go-grpc: clean $(PROTO_OUT) | stable-api printf $(COLOR) "Compile for go-gRPC..." protogen \ --root=$(PROTO_ROOT) \ @@ -79,7 +79,7 @@ fix-path: # We need to rewrite bits of this to support our shorthand payload format # We use both yq and jq here as they preserve comments and the ordering of the original # document -http-api-docs: +http-api-docs: | stable-api protoc -I $(PROTO_ROOT) \ --openapi_out=$(OAPI_OUT) \ --openapi_opt=enum_type=string \ @@ -125,7 +125,7 @@ sync-nexus-annotations: ##### Linters ##### API_LINTER_FMT = 'map(select(.problems != []) | . as $$file | .problems[] | {rule: .rule_doc_uri, location: "\($$file.file_path):\(.location.start_position.line_number)"}) | group_by(.rule) | .[] | .[0].rule + ":\n" + (map("\t" + .location) | join("\n"))' -api-linter: +api-linter: | stable-api printf $(COLOR) "Run api-linter on temporal/api_next..." @api-linter --set-exit-status $(PROTO_IMPORTS) --config $(PROTO_ROOT)/api-linter.yaml --output-format json $(PROTO_FILES_NEXT) | gojq -r $(API_LINTER_FMT) printf $(COLOR) "Run api-linter on temporal/api..." @@ -133,7 +133,7 @@ api-linter: # Every RPC needs a temporal-resource-id request_header annotation for routing, or an entry in # cmd/protoc-gen-resource-id-lint/exemptions.go. -resource-id-lint: resource-id-lint-install +resource-id-lint: resource-id-lint-install | stable-api printf $(COLOR) "Check temporal-resource-id annotations..." protoc $(PROTO_IMPORTS) \ --resource-id-lint_out=. \ @@ -146,16 +146,16 @@ resource-id-lint-install: $(STAMPDIR): mkdir $@ -$(STAMPDIR)/buf-dep-prune: $(STAMPDIR) buf.yaml +$(STAMPDIR)/buf-dep-prune: $(STAMPDIR) buf.yaml | stable-api printf $(COLOR) "Pruning buf module" buf dep prune touch $@ -buf-lint: $(STAMPDIR)/buf-dep-prune +buf-lint: $(STAMPDIR)/buf-dep-prune | stable-api printf $(COLOR) "Run buf linter..." (cd $(PROTO_ROOT) && buf lint) -buf-breaking: +buf-breaking: | stable-api @printf $(COLOR) "Run buf breaking changes check for stable API against main branch..." @(cd $(PROTO_ROOT) && buf breaking --against '$(BUF_BREAKING_AGAINST)') @printf $(COLOR) "Run buf breaking changes check for api_next against main branch..." @@ -163,7 +163,7 @@ buf-breaking: @printf $(COLOR) "Run buf breaking changes check for api_next against previous api_next..." @(cd $(PROTO_ROOT) && bash scripts/check-api-next-breaking.sh '$(BUF_BREAKING_AGAINST)') -nexus-rpc-yaml: nexus-rpc-yaml-install +nexus-rpc-yaml: nexus-rpc-yaml-install | stable-api printf $(COLOR) "Generate nexus/temporal-proto-models-nexusrpc.yaml..." mkdir -p nexus protoc -I $(PROTO_ROOT) \ @@ -180,7 +180,7 @@ nexus-rpc-yaml-install: @cd cmd/protoc-gen-nexus-rpc-yaml && go install . ##### Compile system Nexus WIT files ##### -system-nexus-wit: system-nexus-wit-install nex-gen-install +system-nexus-wit: system-nexus-wit-install nex-gen-install | stable-api printf $(COLOR) "Generate system Nexus WIT..." tmp=$$(mktemp -d); trap 'rm -rf "$$tmp"' EXIT; \ protoc -I $(PROTO_ROOT) --include_imports \ From 2f3471119d83a310d9b25bb8f74511e8577a8fbc Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Fri, 20 Nov 2026 15:26:36 -0700 Subject: [PATCH 03/18] api_next: renumber the demo user draft fields What Moves the draft `Response.user` field to tag 3 and clarifies the comments on both draft user fields. Why The examples need usable tags and a clear description of the user who triggered the update before any draft bindings are published. Co-Authored-By: Claude Opus 5.5 --- temporal/api_next/update/v1/message.proto | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/temporal/api_next/update/v1/message.proto b/temporal/api_next/update/v1/message.proto index ff0250df6..7a8da4f74 100644 --- a/temporal/api_next/update/v1/message.proto +++ b/temporal/api_next/update/v1/message.proto @@ -72,7 +72,7 @@ message Request { repeated temporal.api.common.v1.Link links = 5; // Serialization context propagated from the Nexus caller that started this update. temporal.api.nexus.v1.PropagatedSerializationContext propagated_nexus_serialization_context = 6; - // User to be associated with this request. + // User that triggered the update. string user = 7 [(temporal.api.protometa.v1.draft) = "update-user-tagging"]; } @@ -97,6 +97,6 @@ message Acceptance { message Response { Meta meta = 1; Outcome outcome = 2; - // User that triggered the original user. - string user = 6 [(temporal.api.protometa.v1.draft) = "update-user-tagging"]; + // User that triggered the update. + string user = 3 [(temporal.api.protometa.v1.draft) = "update-user-tagging"]; } From 33f185a4208b5d9c9900812d8b131165df62aa9b Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Fri, 20 Nov 2026 15:26:36 -0700 Subject: [PATCH 04/18] README: describe the api_next workflow and draft annotations What Documents where to edit the source schema, how to regenerate the stable tree, and what the draft annotations do. Why Contributors need a valid path and regeneration workflow when changing the protobuf schema. Co-Authored-By: Claude Opus 5.5 --- README.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7042bc4d4..8fe897571 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,15 @@ Install as git submodule to the project. ## Contribution -Make your change to the temporal/api_next/proto files, and run `make` to update the openapi definitions. +Edit proto files under `temporal/api_next/`. Run `make stable-api` to regenerate `temporal/api/`, or run +`make` to also update the OpenAPI definitions. Do not edit `temporal/api/` by hand. Commit the regenerated +tree with your changes because CI fails if it is stale. + +Use the `draft` field option or the `draft_message` message option from +[`temporal/api_next/protometa/v1/draft.proto`](temporal/api_next/protometa/v1/draft.proto) to mark draft +declarations. For example, `string user = 7 [(temporal.api.protometa.v1.draft) = "update-user-tagging"];` +is a draft field. The generator removes annotated declarations from the stable tree. + Rust is also required because `make` installs and runs `nex-gen` when regenerating system Nexus WIT files. ## Breaking changes From f93b950209c0bc7813111fba61ea8b5f099cd660 Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Fri, 20 Nov 2026 08:12:27 -0700 Subject: [PATCH 05/18] generate-stable-protos: pass context into stableProtosGenerator What Passes a caller-supplied context into `stableProtosGenerator`. Why Tests and other callers can control the lifetime of generator work. Co-Authored-By: Claude Opus 5.5 --- cmd/generate-stable-protos/comments_test.go | 2 +- cmd/generate-stable-protos/main.go | 5 ++--- cmd/generate-stable-protos/main_test.go | 6 +++--- cmd/generate-stable-protos/walk_test.go | 2 +- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/cmd/generate-stable-protos/comments_test.go b/cmd/generate-stable-protos/comments_test.go index 13ba0f956..773d5d2f6 100644 --- a/cmd/generate-stable-protos/comments_test.go +++ b/cmd/generate-stable-protos/comments_test.go @@ -68,7 +68,7 @@ func TestDraftCommentOwnership(t *testing.T) { if err := os.WriteFile(filepath.Join(root, fixture), []byte(strings.Replace(string(input), tc.old, tc.new, 1)), 0600); err != nil { t.Fatal(err) } - err := stableProtosGenerator(root, out) + err := stableProtosGenerator(t.Context(), root, out) if tc.want != "" { if err == nil || !strings.Contains(err.Error(), tc.want) { t.Fatalf("want %q, got %v", tc.want, err) diff --git a/cmd/generate-stable-protos/main.go b/cmd/generate-stable-protos/main.go index 02fedd7cf..5845071ce 100644 --- a/cmd/generate-stable-protos/main.go +++ b/cmd/generate-stable-protos/main.go @@ -48,14 +48,13 @@ func main() { *outDir = *root } - if err := stableProtosGenerator(*root, *outDir); err != nil { + if err := stableProtosGenerator(context.Background(), *root, *outDir); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } -func stableProtosGenerator(root, outDir string) error { - ctx := context.Background() +func stableProtosGenerator(ctx context.Context, root, outDir string) error { paths, err := getAPINextPaths(root) if err != nil { return err diff --git a/cmd/generate-stable-protos/main_test.go b/cmd/generate-stable-protos/main_test.go index fa7a6e779..c5813849d 100644 --- a/cmd/generate-stable-protos/main_test.go +++ b/cmd/generate-stable-protos/main_test.go @@ -17,7 +17,7 @@ func TestStableProjection(t *testing.T) { expected := readTree(t, filepath.Join("testdata", fixture, "expected")) for range 2 { out := t.TempDir() - if err := stableProtosGenerator(filepath.Join("testdata", fixture, "input"), out); err != nil { + if err := stableProtosGenerator(t.Context(), filepath.Join("testdata", fixture, "input"), out); err != nil { t.Fatal(err) } formatTree(t, out) @@ -48,7 +48,7 @@ func TestAnnotationClassification(t *testing.T) { if err := json.Unmarshal(data, &expected); err != nil { t.Fatal(err) } - err = stableProtosGenerator(filepath.Join(fixture, "input"), t.TempDir()) + err = stableProtosGenerator(t.Context(), filepath.Join(fixture, "input"), t.TempDir()) if expected.Error == "" { if err != nil { t.Fatal(err) @@ -71,7 +71,7 @@ func TestProjectionFailures(t *testing.T) { t.Fatal(err) } before := readTree(t, out) - if err := stableProtosGenerator(filepath.Join("testdata", fixture, "input"), out); err == nil { + if err := stableProtosGenerator(t.Context(), filepath.Join("testdata", fixture, "input"), out); err == nil { t.Fatal("expected invalid input to fail") } if !reflect.DeepEqual(before, readTree(t, out)) { diff --git a/cmd/generate-stable-protos/walk_test.go b/cmd/generate-stable-protos/walk_test.go index 407897cab..2e94f643c 100644 --- a/cmd/generate-stable-protos/walk_test.go +++ b/cmd/generate-stable-protos/walk_test.go @@ -28,7 +28,7 @@ func TestDraftSchemaValidation(t *testing.T) { if err := os.WriteFile(path, []byte(tc.schema), 0600); err != nil { t.Fatal(err) } - err := stableProtosGenerator(root, t.TempDir()) + err := stableProtosGenerator(t.Context(), root, t.TempDir()) if tc.want == "" { if err != nil { t.Fatal(err) From 7bc8f17df5153b5c0507811702fa213cee18d613 Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Fri, 20 Nov 2026 08:01:13 -0700 Subject: [PATCH 06/18] generate-stable-protos: list one draft extendee per line What Lists each draft option on its own line in the extendee table. Why Adding or removing an option becomes a one-line diff. Co-Authored-By: Claude Opus 5.5 --- cmd/generate-stable-protos/tags.go | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/cmd/generate-stable-protos/tags.go b/cmd/generate-stable-protos/tags.go index 2a35953bf..8f9ddc1aa 100644 --- a/cmd/generate-stable-protos/tags.go +++ b/cmd/generate-stable-protos/tags.go @@ -20,11 +20,15 @@ type draftTags map[ir.FullName]struct{} func getDraftTags(file *ir.File) (draftTags, error) { tags := make(draftTags) extendees := map[string]string{ - "draft": "FieldOptions", "draft_message": "MessageOptions", - "draft_enum": "EnumOptions", "draft_enum_value": "EnumValueOptions", - "draft_service": "ServiceOptions", "draft_method": "MethodOptions", - "draft_file": "FileOptions", "draft_oneof": "OneofOptions", - "draft_extension": "FieldOptions", + "draft": "FieldOptions", + "draft_message": "MessageOptions", + "draft_enum": "EnumOptions", + "draft_enum_value": "EnumValueOptions", + "draft_service": "ServiceOptions", + "draft_method": "MethodOptions", + "draft_file": "FileOptions", + "draft_oneof": "OneofOptions", + "draft_extension": "FieldOptions", } for ext := range seq.Values(file.AllExtensions()) { name, known := extendees[ext.Name()] From 1d19a9eca305a106891d352dbaa8eade40397de5 Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Sat, 21 Nov 2026 09:23:49 -0700 Subject: [PATCH 07/18] generate-stable-protos: extract loadAPINext from stripDrafts What Extracts schema loading and annotation validation into `loadAPINext`. Why Tests can load and validate a tree without generating stable files. Co-Authored-By: Claude Opus 5.5 --- cmd/generate-stable-protos/main.go | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/cmd/generate-stable-protos/main.go b/cmd/generate-stable-protos/main.go index 5845071ce..39d9a3983 100644 --- a/cmd/generate-stable-protos/main.go +++ b/cmd/generate-stable-protos/main.go @@ -94,11 +94,13 @@ func stableProtosGenerator(ctx context.Context, root, outDir string) error { return writeFiles(outDir, stableProtos) } -func stripDrafts(ctx context.Context, root string, paths []string) ([]string, map[string]string, map[string]draftComments, error) { +// loadAPINext lowers the api_next corpus, discovers the draft-tag extension set and +// validates every draft annotation. +func loadAPINext(ctx context.Context, root string, paths []string) (map[string]*ir.File, draftTags, error) { // first, lower the api_next set into ir results, err := lowerFiles(ctx, baseOpener(root), paths) if err != nil { - return nil, nil, nil, fmt.Errorf("lower api_next corpus: %w", err) + return nil, nil, fmt.Errorf("lower api_next corpus: %w", err) } // need to iterate to find the draft proto- also check @@ -106,16 +108,16 @@ func stripDrafts(ctx context.Context, root string, paths []string) ([]string, ma byPath := make(map[string]*ir.File, len(paths)) for i, p := range paths { if results[i].Fatal != nil { - return nil, nil, nil, fmt.Errorf("%s: %w", p, results[i].Fatal) + return nil, nil, fmt.Errorf("%s: %w", p, results[i].Fatal) } irFile := results[i].Value if got := irFile.Path(); got != p { - return nil, nil, nil, fmt.Errorf("internal error: incremental.Run result %d has path %q, expected %q", i, got, p) + return nil, nil, fmt.Errorf("internal error: incremental.Run result %d has path %q, expected %q", i, got, p) } for imp := range seq.Values(irFile.Imports()) { // Draft options reached through a public re-export would leak it into the stable tree. if imp.Direct && imp.Public && imp.Path() == draftTagsPath { - return nil, nil, nil, fmt.Errorf("%s: public import of %s is not supported; import it directly", p, draftTagsPath) + return nil, nil, fmt.Errorf("%s: public import of %s is not supported; import it directly", p, draftTagsPath) } } byPath[p] = irFile @@ -123,17 +125,25 @@ func stripDrafts(ctx context.Context, root string, paths []string) ([]string, ma draftFile, ok := byPath[draftTagsPath] if !ok { - return nil, nil, nil, fmt.Errorf("%s not found in the corpus; cannot discover the draft-tag extension set", draftTagsPath) + return nil, nil, fmt.Errorf("%s not found in the corpus; cannot discover the draft-tag extension set", draftTagsPath) } tags, err := getDraftTags(draftFile) if err != nil { - return nil, nil, nil, err + return nil, nil, err } for _, p := range paths { if err := validateDraftAnnotations(tags, byPath[p]); err != nil { - return nil, nil, nil, err + return nil, nil, err } } + return byPath, tags, nil +} + +func stripDrafts(ctx context.Context, root string, paths []string) ([]string, map[string]string, map[string]draftComments, error) { + byPath, tags, err := loadAPINext(ctx, root, paths) + if err != nil { + return nil, nil, nil, err + } stableOrder := make([]string, 0, len(paths)) protoTexts := make(map[string]string, len(paths)) From dd7bd5cac8149d72146ce5b042f03e69933e5e4f Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Sat, 21 Nov 2026 09:24:15 -0700 Subject: [PATCH 08/18] generate-stable-protos: normalize comment style What Rephrases generator comments as full sentences and uses declaration names in Go doc comments. Why Consistent comment style makes the generator easier to read. Co-Authored-By: Claude Opus 5.5 --- cmd/generate-stable-protos/comments.go | 14 +++++++------- cmd/generate-stable-protos/main.go | 20 ++++++++++---------- cmd/generate-stable-protos/opener.go | 18 +++++++++--------- cmd/generate-stable-protos/walk.go | 2 +- 4 files changed, 27 insertions(+), 27 deletions(-) diff --git a/cmd/generate-stable-protos/comments.go b/cmd/generate-stable-protos/comments.go index 051ffe270..748195088 100644 --- a/cmd/generate-stable-protos/comments.go +++ b/cmd/generate-stable-protos/comments.go @@ -51,14 +51,14 @@ func findDraftComments(f *ir.File, dels []ast.DeclAny) (draftComments, error) { } // checkCommentsAfter rejects comments between a removed declaration and the next code. -// protoc attaches such comments to the removed declaration or to nothing, and the printer -// then keeps them. Only a comment on the declaration's own last line, or the doc block -// directly above the next surviving declaration, may sit there. +// The protoc compiler attaches such comments to the removed declaration or to nothing, +// and the printer then keeps them. Only a comment on the declaration's own last line, +// or the doc block directly above the next surviving declaration, may sit there. func checkCommentsAfter(f *ir.File, dels []ast.DeclAny) error { removed := func(offset int) bool { return slices.ContainsFunc(dels, func(d ast.DeclAny) bool { return d.Span().Start <= offset && offset < d.Span().End }) } - // LeafSpan, because the Span of a brace pair covers its whole body. + // Use LeafSpan because the Span of a brace pair covers its whole body. line := func(tok token.Token) int { return tok.LeafSpan().StartLoc().Line } lastLine := func(c token.Token) int { return line(c) + strings.Count(strings.TrimRight(c.Text(), "\n"), "\n") @@ -81,7 +81,7 @@ func checkCommentsAfter(f *ir.File, dels []ast.DeclAny) error { } } if found && removed(next.LeafSpan().Start) { - continue // these belong to the next removed declaration and are checked through it + continue // These comments are checked with the next removed declaration, to which they belong. } doc := len(gap) if found && !closesScope(next) { @@ -98,8 +98,8 @@ func checkCommentsAfter(f *ir.File, dels []ast.DeclAny) error { return nil } -// closesScope reports whether tok is the closing token of a pair such as "}"; Text -// returns the open token's text for both ends. +// closesScope reports whether tok is the closing token of a pair such as "}". +// Text returns the open token's text for both ends. func closesScope(tok token.Token) bool { if tok.IsLeaf() { return false diff --git a/cmd/generate-stable-protos/main.go b/cmd/generate-stable-protos/main.go index 39d9a3983..edd042e97 100644 --- a/cmd/generate-stable-protos/main.go +++ b/cmd/generate-stable-protos/main.go @@ -68,8 +68,8 @@ func stableProtosGenerator(ctx context.Context, root, outDir string) error { return err } - // import stripping has to happen after the draft-tagged declarations are deleted - // because unused imports are only detectable after it is re-rendered + // Strip unused imports after deleting draft-tagged declarations and re-rendering the protos, + // because only then can we detect which imports are unused. stableProtos, err := organizeImports(ctx, root, strippedOrder, strippedProtos) if err != nil { return err @@ -97,7 +97,7 @@ func stableProtosGenerator(ctx context.Context, root, outDir string) error { // loadAPINext lowers the api_next corpus, discovers the draft-tag extension set and // validates every draft annotation. func loadAPINext(ctx context.Context, root string, paths []string) (map[string]*ir.File, draftTags, error) { - // first, lower the api_next set into ir + // First, lower the api_next corpus into IR. results, err := lowerFiles(ctx, baseOpener(root), paths) if err != nil { return nil, nil, fmt.Errorf("lower api_next corpus: %w", err) @@ -115,7 +115,7 @@ func loadAPINext(ctx context.Context, root string, paths []string) (map[string]* return nil, nil, fmt.Errorf("internal error: incremental.Run result %d has path %q, expected %q", i, got, p) } for imp := range seq.Values(irFile.Imports()) { - // Draft options reached through a public re-export would leak it into the stable tree. + // A public re-export of the draft options proto would leak it into the stable tree. if imp.Direct && imp.Public && imp.Path() == draftTagsPath { return nil, nil, fmt.Errorf("%s: public import of %s is not supported; import it directly", p, draftTagsPath) } @@ -150,7 +150,7 @@ func stripDrafts(ctx context.Context, root string, paths []string) ([]string, ma comments := make(map[string]draftComments, len(paths)) for _, p := range paths { irFile := byPath[p] - // skip draft.proto itself + // Skip draft.proto itself. if p == draftTagsPath { continue } @@ -177,7 +177,7 @@ func stripDrafts(ctx context.Context, root string, paths []string) ([]string, ma return stableOrder, protoTexts, comments, nil } -// strip unused imports and rename import to stable (api_next -> api) +// organizeImports removes unused imports and rewrites api_next import paths to their stable api paths. func organizeImports(ctx context.Context, root string, order []string, texts map[string]string) (map[string]string, error) { results, err := lowerFiles(ctx, memOpener(root, texts), order) if err != nil { @@ -213,7 +213,7 @@ func organizeImports(ctx context.Context, root string, order []string, texts map return stableTexts, nil } -// re-lower one more time to ensure there are no compilation issues +// verifyGeneratedProtos lowers the generated protos again to check for compilation errors. func verifyGeneratedProtos(ctx context.Context, root string, stableTexts map[string]string) error { paths := make([]string, 0, len(stableTexts)) for p := range stableTexts { @@ -233,7 +233,7 @@ func verifyGeneratedProtos(ctx context.Context, root string, stableTexts map[str return jErr } -// lowerFiles lowers paths in one session; each pass must construct its opener once. +// lowerFiles lowers paths in one session. Each pass must construct its opener once. func lowerFiles(ctx context.Context, opener source.Opener, paths []string) ([]incremental.Result[*ir.File], error) { session := &ir.Session{} lowerQueries := make([]incremental.Query[*ir.File], len(paths)) @@ -250,7 +250,7 @@ func lowerFiles(ctx context.Context, opener source.Opener, paths []string) ([]in return results, nil } -// TODO: check if the buf formatter rules can just get pulled into a custom formatter +// TODO: Check whether a custom formatter can reuse Buf's formatting rules. func printFile(file *ir.File) (string, error) { return printer.PrintFile(printer.Options{Format: true, Formatting: printer.Legacy()}, file.AST()) } @@ -334,7 +334,7 @@ func rewriteImportPaths(text string) (string, error) { if err := prototext.Unmarshal([]byte("value: "+partSpan.Text()), &part); err != nil { return "", fmt.Errorf("decode import literal: %w", err) } - // The _next suffix can straddle concatenated literals; preserve their comments. + // The _next suffix can straddle concatenated literals. Preserve their comments. from := max(len(stableAPIPrefix)-1-offset, 0) to := min(len(apiNextPrefix)-1-offset, len(part.Value)) offset += len(part.Value) diff --git a/cmd/generate-stable-protos/opener.go b/cmd/generate-stable-protos/opener.go index 9f9052ba2..ea41e2cd0 100644 --- a/cmd/generate-stable-protos/opener.go +++ b/cmd/generate-stable-protos/opener.go @@ -12,10 +12,10 @@ func diskOpener(root string) source.Opener { return &source.FS{FS: os.DirFS(root)} } -// baseOpener is the disk corpus plus well-known types, shared by every pass -// that reads real files unmodified (currently just stripDraftChanges, +// baseOpener serves the disk corpus and well-known types. Every pass that +// reads real files unmodified uses it (currently just stripDraftChanges, // which lowers the authored api_next tree as-is). Construct this once per -// pass and share it across every query in that pass; see the comparability +// pass and share it across every query in that pass. See the comparability // note on memOpener below for why. func baseOpener(root string) source.Opener { return &source.Openers{source.WKTs(), diskOpener(root)} @@ -23,15 +23,15 @@ func baseOpener(root string) source.Opener { // memOpener serves an entire in-memory set of final texts (keyed by their // paths in whatever path space the caller is currently working in) ahead -// of the disk corpus and WKTs. Used by stripUnusedImports (re-lowering -// draft-stripped text) and verifyStrippedProtos (combined cross-file -// verification of the final stable tree). +// of the disk corpus and WKTs. The stripUnusedImports pass uses it to +// re-lower draft-stripped text, and verifyStrippedProtos uses it for +// cross-file verification of the final stable tree. // -// source.Opener implementations must be comparable: an Opener value is -// part of queries.IR's cache key (see queries.IR.Key() in protocompile). +// Implementations of source.Opener must be comparable because an Opener value +// is part of queries.IR's cache key (see queries.IR.Key() in protocompile). // Every constructor in this file therefore returns a pointer, and callers // must call the constructor exactly ONCE per lowering pass and share the -// resulting Opener across every query in that pass -- calling it again +// resulting Opener across every query in that pass. Calling it again // (even with identical contents) yields a distinct pointer, hence a // distinct cache key, forcing protocompile to re-lower the whole corpus. func memOpener(root string, files map[string]string) source.Opener { diff --git a/cmd/generate-stable-protos/walk.go b/cmd/generate-stable-protos/walk.go index 98f7659fb..8dbc82aff 100644 --- a/cmd/generate-stable-protos/walk.go +++ b/cmd/generate-stable-protos/walk.go @@ -42,7 +42,7 @@ func walkType(tags draftTags, t ir.Type, dels *[]ast.DeclAny) { } } for nested := range seq.Values(t.Nested()) { - // Synthetic map entries share the field's AST, already handled above. + // Synthetic map entries share the AST of the field handled above. if !nested.IsMapEntry() { walkType(tags, nested, dels) } From 5d0850dca424d9e9960afe24eee8977f1ac76a7d Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Sat, 21 Nov 2026 09:24:15 -0700 Subject: [PATCH 09/18] generate-stable-protos: clarify generator comment details What Removes stale opener caller names and documents file indexing and the legacy formatter. Why The comments should explain the current implementation and its constraints. Co-Authored-By: Claude Opus 5.5 --- cmd/generate-stable-protos/main.go | 5 +++-- cmd/generate-stable-protos/opener.go | 10 +++------- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/cmd/generate-stable-protos/main.go b/cmd/generate-stable-protos/main.go index edd042e97..47eefbfe8 100644 --- a/cmd/generate-stable-protos/main.go +++ b/cmd/generate-stable-protos/main.go @@ -103,8 +103,7 @@ func loadAPINext(ctx context.Context, root string, paths []string) (map[string]* return nil, nil, fmt.Errorf("lower api_next corpus: %w", err) } - // need to iterate to find the draft proto- also check - // for errors while iterating so it doesnt have to be repeated + // Check for errors while indexing files by path so we can look up the draft proto in one pass. byPath := make(map[string]*ir.File, len(paths)) for i, p := range paths { if results[i].Fatal != nil { @@ -250,6 +249,8 @@ func lowerFiles(ctx context.Context, opener source.Opener, paths []string) ([]in return results, nil } +// printFile formats the file with the legacy formatter. +// // TODO: Check whether a custom formatter can reuse Buf's formatting rules. func printFile(file *ir.File) (string, error) { return printer.PrintFile(printer.Options{Format: true, Formatting: printer.Legacy()}, file.AST()) diff --git a/cmd/generate-stable-protos/opener.go b/cmd/generate-stable-protos/opener.go index ea41e2cd0..90765f0e4 100644 --- a/cmd/generate-stable-protos/opener.go +++ b/cmd/generate-stable-protos/opener.go @@ -12,10 +12,8 @@ func diskOpener(root string) source.Opener { return &source.FS{FS: os.DirFS(root)} } -// baseOpener serves the disk corpus and well-known types. Every pass that -// reads real files unmodified uses it (currently just stripDraftChanges, -// which lowers the authored api_next tree as-is). Construct this once per -// pass and share it across every query in that pass. See the comparability +// baseOpener serves the disk corpus and well-known types. Construct this once +// per pass and share it across every query in that pass. See the comparability // note on memOpener below for why. func baseOpener(root string) source.Opener { return &source.Openers{source.WKTs(), diskOpener(root)} @@ -23,9 +21,7 @@ func baseOpener(root string) source.Opener { // memOpener serves an entire in-memory set of final texts (keyed by their // paths in whatever path space the caller is currently working in) ahead -// of the disk corpus and WKTs. The stripUnusedImports pass uses it to -// re-lower draft-stripped text, and verifyStrippedProtos uses it for -// cross-file verification of the final stable tree. +// of the disk corpus and WKTs. // // Implementations of source.Opener must be comparable because an Opener value // is part of queries.IR's cache key (see queries.IR.Key() in protocompile). From 75d047ffc0dd47a84ac0cb5bc950ed329a38ea9a Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Sat, 21 Nov 2026 09:24:31 -0700 Subject: [PATCH 10/18] generate-stable-protos: return sorted paths from draft stripping What Derives sorted paths from the projected proto map in stripDrafts and reuses that order for import organization and comment validation. Why Both passes process the same files, so the generator can sort them once and give callers the complete order. Co-Authored-By: Claude Opus 5.5 --- cmd/generate-stable-protos/main.go | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/cmd/generate-stable-protos/main.go b/cmd/generate-stable-protos/main.go index 47eefbfe8..702f067b1 100644 --- a/cmd/generate-stable-protos/main.go +++ b/cmd/generate-stable-protos/main.go @@ -6,8 +6,10 @@ import ( "flag" "fmt" "io/fs" + "maps" "os" "path/filepath" + "slices" "sort" "strconv" "strings" @@ -144,7 +146,6 @@ func stripDrafts(ctx context.Context, root string, paths []string) ([]string, ma return nil, nil, nil, err } - stableOrder := make([]string, 0, len(paths)) protoTexts := make(map[string]string, len(paths)) comments := make(map[string]draftComments, len(paths)) for _, p := range paths { @@ -171,9 +172,8 @@ func stripDrafts(ctx context.Context, root string, paths []string) ([]string, ma } protoTexts[p] = protoText - stableOrder = append(stableOrder, p) } - return stableOrder, protoTexts, comments, nil + return slices.Sorted(maps.Keys(protoTexts)), protoTexts, comments, nil } // organizeImports removes unused imports and rewrites api_next import paths to their stable api paths. @@ -214,11 +214,7 @@ func organizeImports(ctx context.Context, root string, order []string, texts map // verifyGeneratedProtos lowers the generated protos again to check for compilation errors. func verifyGeneratedProtos(ctx context.Context, root string, stableTexts map[string]string) error { - paths := make([]string, 0, len(stableTexts)) - for p := range stableTexts { - paths = append(paths, p) - } - sort.Strings(paths) + paths := slices.Sorted(maps.Keys(stableTexts)) results, err := lowerFiles(ctx, memOpener(root, stableTexts), paths) if err != nil { return fmt.Errorf("verify stable tree failed: %w", err) From 088ad8b792260e9d0184b103655d74bae7fb6eeb Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Sat, 21 Nov 2026 09:24:33 -0700 Subject: [PATCH 11/18] generate-stable-protos: rename jErr to errs What Renames the verification error slice from `jErr` to `errs`. Why The name reflects that the slice holds individual errors until they are joined. Co-Authored-By: Claude Opus 5.5 --- cmd/generate-stable-protos/main.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cmd/generate-stable-protos/main.go b/cmd/generate-stable-protos/main.go index 702f067b1..4a99c63bf 100644 --- a/cmd/generate-stable-protos/main.go +++ b/cmd/generate-stable-protos/main.go @@ -219,13 +219,13 @@ func verifyGeneratedProtos(ctx context.Context, root string, stableTexts map[str if err != nil { return fmt.Errorf("verify stable tree failed: %w", err) } - var jErr error + var errs error for i, r := range results { if r.Fatal != nil { - jErr = errors.Join(jErr, fmt.Errorf("verification failed at file %q: %w", paths[i], r.Fatal)) + errs = errors.Join(errs, fmt.Errorf("verification failed at file %q: %w", paths[i], r.Fatal)) } } - return jErr + return errs } // lowerFiles lowers paths in one session. Each pass must construct its opener once. From 06e19078e32f47e19c4a11c2f45055c10bafd6ae Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Sat, 21 Nov 2026 09:32:11 -0700 Subject: [PATCH 12/18] generate-stable-protos: run tests in parallel What Runs generator tests and subtests in parallel. Why The tests use independent temporary directories, so they can run concurrently. Co-Authored-By: Claude Opus 5.5 --- cmd/generate-stable-protos/breaking_test.go | 4 ++++ cmd/generate-stable-protos/comments_test.go | 2 ++ cmd/generate-stable-protos/main_test.go | 9 +++++++++ cmd/generate-stable-protos/walk_test.go | 2 ++ 4 files changed, 17 insertions(+) diff --git a/cmd/generate-stable-protos/breaking_test.go b/cmd/generate-stable-protos/breaking_test.go index e961a0cfa..51acebce4 100644 --- a/cmd/generate-stable-protos/breaking_test.go +++ b/cmd/generate-stable-protos/breaking_test.go @@ -9,6 +9,7 @@ import ( ) func TestDraftBreakingReservations(t *testing.T) { + t.Parallel() config, err := filepath.Abs("../../buf.next.yaml") if err != nil { t.Fatal(err) @@ -47,6 +48,7 @@ message Example { %s } {"promoted", "string value = 1;", nil}, } { t.Run(tc.name, func(t *testing.T) { + t.Parallel() after := image(t, tc.field) out, err := exec.Command("buf", "breaking", after, "--against", before, "--config", config).CombinedOutput() if len(tc.want) == 0 { @@ -68,6 +70,7 @@ message Example { %s } } func TestDraftBreakingBootstrap(t *testing.T) { + t.Parallel() root, err := filepath.Abs("../..") if err != nil { t.Fatal(err) @@ -82,6 +85,7 @@ func TestDraftBreakingBootstrap(t *testing.T) { {"invalid draft history naming the bootstrap phrase", "temporal/api_next/no .proto files/example.proto", "invalid proto", false}, } { t.Run(tc.name, func(t *testing.T) { + t.Parallel() baseline := t.TempDir() path := filepath.Join(baseline, tc.path) if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { diff --git a/cmd/generate-stable-protos/comments_test.go b/cmd/generate-stable-protos/comments_test.go index 773d5d2f6..37e2590bb 100644 --- a/cmd/generate-stable-protos/comments_test.go +++ b/cmd/generate-stable-protos/comments_test.go @@ -12,6 +12,7 @@ import ( // after it that protoc attaches to nothing. The passing case also pins the raw printer // output, which TestStableProjection cannot see because it runs buf format first. func TestDraftCommentOwnership(t *testing.T) { + t.Parallel() const fixture = "temporal/api_next/fixture.proto" const after = `after a removed draft declaration would survive in the stable output; move it directly above a declaration, or delete it` input, err := os.ReadFile(filepath.Join("testdata/comments/input", fixture)) @@ -58,6 +59,7 @@ func TestDraftCommentOwnership(t *testing.T) { }, } { t.Run(tc.name, func(t *testing.T) { + t.Parallel() root, out := t.TempDir(), t.TempDir() if err := os.CopyFS(root, os.DirFS("testdata/comments/input")); err != nil { t.Fatal(err) diff --git a/cmd/generate-stable-protos/main_test.go b/cmd/generate-stable-protos/main_test.go index c5813849d..436371d8f 100644 --- a/cmd/generate-stable-protos/main_test.go +++ b/cmd/generate-stable-protos/main_test.go @@ -12,8 +12,10 @@ import ( ) func TestStableProjection(t *testing.T) { + t.Parallel() for _, fixture := range []string{"classification/valid", "classification/message-types", "imports"} { t.Run(fixture, func(t *testing.T) { + t.Parallel() expected := readTree(t, filepath.Join("testdata", fixture, "expected")) for range 2 { out := t.TempDir() @@ -31,12 +33,14 @@ func TestStableProjection(t *testing.T) { } func TestAnnotationClassification(t *testing.T) { + t.Parallel() dirs, err := os.ReadDir("testdata/classification") if err != nil { t.Fatal(err) } for _, dir := range dirs { t.Run(dir.Name(), func(t *testing.T) { + t.Parallel() fixture := filepath.Join("testdata/classification", dir.Name()) data, err := os.ReadFile(filepath.Join(fixture, "expected.json")) if err != nil { @@ -63,8 +67,10 @@ func TestAnnotationClassification(t *testing.T) { } func TestProjectionFailures(t *testing.T) { + t.Parallel() for _, fixture := range []string{"dangling", "missing"} { t.Run(fixture, func(t *testing.T) { + t.Parallel() out := t.TempDir() sentinel := filepath.Join(out, "retained") if err := os.WriteFile(sentinel, []byte("old"), 0600); err != nil { @@ -82,6 +88,7 @@ func TestProjectionFailures(t *testing.T) { } func TestRewriteImportPaths(t *testing.T) { + t.Parallel() input := `syntax = "proto3"; import public /* before */ 'temporal/api_next/used.proto' /* after */; import "google/protobuf/any.proto"; @@ -109,12 +116,14 @@ option java_package = "temporal/api_next/used.proto"; } func TestStableReplacement(t *testing.T) { + t.Parallel() script, err := filepath.Abs("../../scripts/stable-api.sh") if err != nil { t.Fatal(err) } for _, failure := range []string{"generation", "formatting", "replacement", "none"} { t.Run(failure, func(t *testing.T) { + t.Parallel() root := t.TempDir() tools := t.TempDir() if err := os.MkdirAll(filepath.Join(root, "temporal/api/nested"), 0755); err != nil { diff --git a/cmd/generate-stable-protos/walk_test.go b/cmd/generate-stable-protos/walk_test.go index 2e94f643c..243fdf638 100644 --- a/cmd/generate-stable-protos/walk_test.go +++ b/cmd/generate-stable-protos/walk_test.go @@ -8,6 +8,7 @@ import ( ) func TestDraftSchemaValidation(t *testing.T) { + t.Parallel() schema, err := os.ReadFile("testdata/classification/valid/input/temporal/api_next/protometa/v1/draft.proto") if err != nil { t.Fatal(err) @@ -20,6 +21,7 @@ func TestDraftSchemaValidation(t *testing.T) { {"unrelated extension", string(schema) + "extend google.protobuf.FileOptions { bool draft_notes = 98112; }\n", ""}, } { t.Run(tc.name, func(t *testing.T) { + t.Parallel() root := t.TempDir() path := filepath.Join(root, draftTagsPath) if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { From 1b691f3dbe19106759b7057d648d42fc113867d4 Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Sat, 21 Nov 2026 09:33:44 -0700 Subject: [PATCH 13/18] generate-stable-protos: assert classified draft annotations What Collects accepted draft annotations and compares their declarations and feature names against the fixtures. Why A validator can accept valid input while still classifying a declaration under the wrong feature. Co-Authored-By: Claude Opus 5.5 --- cmd/generate-stable-protos/main.go | 27 +++++++++-------- cmd/generate-stable-protos/main_test.go | 18 +++++++++-- cmd/generate-stable-protos/tags.go | 30 ++++++++++++------- .../message-types/expected.json | 8 ++--- .../classification/message/expected.json | 2 +- .../classification/valid/expected.json | 2 +- 6 files changed, 55 insertions(+), 32 deletions(-) diff --git a/cmd/generate-stable-protos/main.go b/cmd/generate-stable-protos/main.go index 4a99c63bf..c4a4b1166 100644 --- a/cmd/generate-stable-protos/main.go +++ b/cmd/generate-stable-protos/main.go @@ -97,28 +97,28 @@ func stableProtosGenerator(ctx context.Context, root, outDir string) error { } // loadAPINext lowers the api_next corpus, discovers the draft-tag extension set and -// validates every draft annotation. -func loadAPINext(ctx context.Context, root string, paths []string) (map[string]*ir.File, draftTags, error) { +// validates every draft annotation, returning the annotations it accepted. +func loadAPINext(ctx context.Context, root string, paths []string) (map[string]*ir.File, draftTags, draftAnnotations, error) { // First, lower the api_next corpus into IR. results, err := lowerFiles(ctx, baseOpener(root), paths) if err != nil { - return nil, nil, fmt.Errorf("lower api_next corpus: %w", err) + return nil, nil, nil, fmt.Errorf("lower api_next corpus: %w", err) } // Check for errors while indexing files by path so we can look up the draft proto in one pass. byPath := make(map[string]*ir.File, len(paths)) for i, p := range paths { if results[i].Fatal != nil { - return nil, nil, fmt.Errorf("%s: %w", p, results[i].Fatal) + return nil, nil, nil, fmt.Errorf("%s: %w", p, results[i].Fatal) } irFile := results[i].Value if got := irFile.Path(); got != p { - return nil, nil, fmt.Errorf("internal error: incremental.Run result %d has path %q, expected %q", i, got, p) + return nil, nil, nil, fmt.Errorf("internal error: incremental.Run result %d has path %q, expected %q", i, got, p) } for imp := range seq.Values(irFile.Imports()) { // A public re-export of the draft options proto would leak it into the stable tree. if imp.Direct && imp.Public && imp.Path() == draftTagsPath { - return nil, nil, fmt.Errorf("%s: public import of %s is not supported; import it directly", p, draftTagsPath) + return nil, nil, nil, fmt.Errorf("%s: public import of %s is not supported; import it directly", p, draftTagsPath) } } byPath[p] = irFile @@ -126,22 +126,25 @@ func loadAPINext(ctx context.Context, root string, paths []string) (map[string]* draftFile, ok := byPath[draftTagsPath] if !ok { - return nil, nil, fmt.Errorf("%s not found in the corpus; cannot discover the draft-tag extension set", draftTagsPath) + return nil, nil, nil, fmt.Errorf("%s not found in the corpus; cannot discover the draft-tag extension set", draftTagsPath) } tags, err := getDraftTags(draftFile) if err != nil { - return nil, nil, err + return nil, nil, nil, err } + annotations := draftAnnotations{} for _, p := range paths { - if err := validateDraftAnnotations(tags, byPath[p]); err != nil { - return nil, nil, err + accepted, err := validateDraftAnnotations(tags, byPath[p]) + if err != nil { + return nil, nil, nil, err } + maps.Copy(annotations, accepted) } - return byPath, tags, nil + return byPath, tags, annotations, nil } func stripDrafts(ctx context.Context, root string, paths []string) ([]string, map[string]string, map[string]draftComments, error) { - byPath, tags, err := loadAPINext(ctx, root, paths) + byPath, tags, _, err := loadAPINext(ctx, root, paths) if err != nil { return nil, nil, nil, err } diff --git a/cmd/generate-stable-protos/main_test.go b/cmd/generate-stable-protos/main_test.go index 436371d8f..cd8d9b7fa 100644 --- a/cmd/generate-stable-protos/main_test.go +++ b/cmd/generate-stable-protos/main_test.go @@ -3,6 +3,7 @@ package main import ( "encoding/json" "io/fs" + "maps" "os" "os/exec" "path/filepath" @@ -47,16 +48,29 @@ func TestAnnotationClassification(t *testing.T) { t.Fatal(err) } var expected struct { - Error string `json:"error"` + Error string `json:"error"` + Annotations draftAnnotations `json:"annotations"` } if err := json.Unmarshal(data, &expected); err != nil { t.Fatal(err) } - err = stableProtosGenerator(t.Context(), filepath.Join(fixture, "input"), t.TempDir()) + root := filepath.Join(fixture, "input") + err = stableProtosGenerator(t.Context(), root, t.TempDir()) if expected.Error == "" { if err != nil { t.Fatal(err) } + paths, err := getAPINextPaths(root) + if err != nil { + t.Fatal(err) + } + _, _, actual, err := loadAPINext(t.Context(), root, paths) + if err != nil { + t.Fatal(err) + } + if !maps.Equal(expected.Annotations, actual) { + t.Fatalf("draft annotations differ\nexpected: %v\nactual: %v", expected.Annotations, actual) + } return } if err == nil || !strings.Contains(err.Error(), expected.Error) { diff --git a/cmd/generate-stable-protos/tags.go b/cmd/generate-stable-protos/tags.go index 8f9ddc1aa..9fde947e5 100644 --- a/cmd/generate-stable-protos/tags.go +++ b/cmd/generate-stable-protos/tags.go @@ -55,7 +55,14 @@ func (tags draftTags) has(opts ir.MessageValue) bool { return false } -func validateDraftAnnotations(tags draftTags, f *ir.File) error { +type draftAnnotations map[ir.FullName]draftFeature + +type draftFeature = string + +// validateDraftAnnotations rejects unsupported or malformed draft annotations in f and +// returns the accepted ones. +func validateDraftAnnotations(tags draftTags, f *ir.File) (draftAnnotations, error) { + accepted := draftAnnotations{} check := func(name string, placement string, opts ir.MessageValue) error { for v := range opts.Fields() { if _, ok := tags[v.Field().FullName()]; !ok { @@ -69,11 +76,12 @@ func validateDraftAnnotations(tags draftTags, f *ir.File) error { if !ok || feature == "" || strings.ContainsFunc(feature, unicode.IsSpace) { return fmt.Errorf("%s: draft feature must be nonempty and contain no whitespace", name) } + accepted[ir.FullName(name)] = feature } return nil } if err := check(f.Path(), "file", f.Options()); err != nil { - return err + return nil, err } for t := range seq.Values(f.AllTypes()) { placement := "message" @@ -81,7 +89,7 @@ func validateDraftAnnotations(tags draftTags, f *ir.File) error { placement = "enum" } if err := check(string(t.FullName()), placement, t.Options()); err != nil { - return err + return nil, err } for m := range seq.Values(t.Members()) { placement := "field" @@ -89,43 +97,43 @@ func validateDraftAnnotations(tags draftTags, f *ir.File) error { placement = "enum value" } if err := check(string(m.FullName()), placement, m.Options()); err != nil { - return err + return nil, err } } for o := range seq.Values(t.Oneofs()) { if err := check(string(o.FullName()), "oneof", o.Options()); err != nil { - return err + return nil, err } } } for ext := range seq.Values(f.AllExtensions()) { if err := check(string(ext.FullName()), "extension", ext.Options()); err != nil { - return err + return nil, err } for _, t := range []ir.Type{ext.Element(), ext.Container(), ext.Parent()} { if isDraftType(tags, t) { - return fmt.Errorf("%s: extension references draft type %s unsupported by omission", ext.FullName(), t.FullName()) + return nil, fmt.Errorf("%s: extension references draft type %s unsupported by omission", ext.FullName(), t.FullName()) } } } for s := range seq.Values(f.Services()) { if err := check(string(s.FullName()), "service", s.Options()); err != nil { - return err + return nil, err } for m := range seq.Values(s.Methods()) { if err := check(string(m.FullName()), "method", m.Options()); err != nil { - return err + return nil, err } input, _ := m.Input() output, _ := m.Output() for _, t := range []ir.Type{input, output} { if isDraftType(tags, t) { - return fmt.Errorf("%s: RPC references draft type %s unavailable in the stable API", m.FullName(), t.FullName()) + return nil, fmt.Errorf("%s: RPC references draft type %s unavailable in the stable API", m.FullName(), t.FullName()) } } } } - return nil + return accepted, nil } func isDraftType(tags draftTags, t ir.Type) bool { diff --git a/cmd/generate-stable-protos/testdata/classification/message-types/expected.json b/cmd/generate-stable-protos/testdata/classification/message-types/expected.json index d477392ba..719578c09 100644 --- a/cmd/generate-stable-protos/testdata/classification/message-types/expected.json +++ b/cmd/generate-stable-protos/testdata/classification/message-types/expected.json @@ -1,9 +1,7 @@ { - "fields": { - "fixture.Parent.extra": "feature-c" - }, - "messages": { + "annotations": { "fixture.Draft": "feature-a", - "fixture.Draft.Extra": "feature-b" + "fixture.Draft.Extra": "feature-b", + "fixture.Parent.extra": "feature-c" } } diff --git a/cmd/generate-stable-protos/testdata/classification/message/expected.json b/cmd/generate-stable-protos/testdata/classification/message/expected.json index 9410574ea..69c3ac8b8 100644 --- a/cmd/generate-stable-protos/testdata/classification/message/expected.json +++ b/cmd/generate-stable-protos/testdata/classification/message/expected.json @@ -1,5 +1,5 @@ { - "messages": { + "annotations": { "fixture.Example": "feature-a" } } diff --git a/cmd/generate-stable-protos/testdata/classification/valid/expected.json b/cmd/generate-stable-protos/testdata/classification/valid/expected.json index 72cc21fcf..0c140cb07 100644 --- a/cmd/generate-stable-protos/testdata/classification/valid/expected.json +++ b/cmd/generate-stable-protos/testdata/classification/valid/expected.json @@ -1,5 +1,5 @@ { - "fields": { + "annotations": { "fixture.Example.a": "feature-a", "fixture.Example.optional_b": "feature-b", "fixture.Example.draft_choice": "feature-a", From ee2272819c71379c18e3aed20a97aabd350cea1b Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Sat, 21 Nov 2026 09:34:54 -0700 Subject: [PATCH 14/18] generate-stable-protos: run every fixture through one runner What Runs projection, classification, and rejection fixtures through one test runner. Why Every fixture gets the same checks for expected annotations, deterministic output, and failure behavior. Co-Authored-By: Claude Opus 5.5 --- cmd/generate-stable-protos/fixtures_test.go | 136 ++++++++++++++++++ cmd/generate-stable-protos/main_test.go | 100 ------------- .../expected/temporal/api/fixture.proto | 3 - .../expected/temporal/api/types.proto | 3 - .../valid/expected/temporal/api/fixture.proto | 3 - .../testdata/comments/expected.json | 10 ++ .../testdata/dangling/expected.json | 1 + .../testdata/imports/expected.json | 5 + .../imports/expected/temporal/api/root.proto | 4 - .../expected/temporal/api/unused.proto | 3 - .../imports/expected/temporal/api/used.proto | 3 - .../testdata/missing/expected.json | 1 + 12 files changed, 153 insertions(+), 119 deletions(-) create mode 100644 cmd/generate-stable-protos/fixtures_test.go create mode 100644 cmd/generate-stable-protos/testdata/comments/expected.json create mode 100644 cmd/generate-stable-protos/testdata/dangling/expected.json create mode 100644 cmd/generate-stable-protos/testdata/imports/expected.json create mode 100644 cmd/generate-stable-protos/testdata/missing/expected.json diff --git a/cmd/generate-stable-protos/fixtures_test.go b/cmd/generate-stable-protos/fixtures_test.go new file mode 100644 index 000000000..df70164c3 --- /dev/null +++ b/cmd/generate-stable-protos/fixtures_test.go @@ -0,0 +1,136 @@ +package main + +import ( + "encoding/json" + "errors" + "io/fs" + "maps" + "os" + "path/filepath" + "reflect" + "slices" + "strings" + "testing" +) + +// TestFixtures runs the generator on every fixture under testdata. A fixture is a +// directory with an input/ api_next tree, and optionally an expected.json and an +// expected/ tree holding the raw generator output without its generated header. +func TestFixtures(t *testing.T) { + t.Parallel() + for _, fixture := range findFixtures(t) { + t.Run(fixture, func(t *testing.T) { + t.Parallel() + runFixture(t, filepath.Join("testdata", fixture)) + }) + } +} + +// fixtureExpectation is a fixture's expected.json. +type fixtureExpectation struct { + // Error is a substring of the expected generator error; empty means success. + Error string `json:"error"` + // Annotations are the draft annotations the generator must accept. + Annotations draftAnnotations `json:"annotations"` +} + +// findFixtures returns the fixture directories under testdata, relative to it. +func findFixtures(t *testing.T) []string { + t.Helper() + var fixtures []string + if err := filepath.WalkDir("testdata", func(path string, entry fs.DirEntry, err error) error { + if err != nil || !entry.IsDir() { + return err + } + for _, marker := range []string{"input", "expected.json"} { + if _, err := os.Stat(filepath.Join(path, marker)); err == nil { + relative, err := filepath.Rel("testdata", path) + if err != nil { + return err + } + fixtures = append(fixtures, filepath.ToSlash(relative)) + return filepath.SkipDir + } + } + return nil + }); err != nil { + t.Fatal(err) + } + return fixtures +} + +func runFixture(t *testing.T, dir string) { + t.Helper() + var expected fixtureExpectation + if data, err := os.ReadFile(filepath.Join(dir, "expected.json")); err == nil { + if err := json.Unmarshal(data, &expected); err != nil { + t.Fatal(err) + } + } else if !errors.Is(err, fs.ErrNotExist) { + t.Fatal(err) + } + root := filepath.Join(dir, "input") + out := t.TempDir() + + if expected.Error != "" { + sentinel := map[string]string{"retained": "old"} + if err := os.WriteFile(filepath.Join(out, "retained"), []byte("old"), 0o600); err != nil { + t.Fatal(err) + } + err := stableProtosGenerator(t.Context(), root, out) + if err == nil || !strings.Contains(err.Error(), expected.Error) { + t.Fatalf("want error %q, got %v", expected.Error, err) + } + if !reflect.DeepEqual(sentinel, readTree(t, out)) { + t.Fatal("generation failure modified output") + } + return + } + + if err := stableProtosGenerator(t.Context(), root, out); err != nil { + t.Fatal(err) + } + actual := readTree(t, out) + again := t.TempDir() + if err := stableProtosGenerator(t.Context(), root, again); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(actual, readTree(t, again)) { + t.Fatal("generator output is not deterministic") + } + + paths, err := getAPINextPaths(root) + if err != nil { + t.Fatal(err) + } + _, _, annotations, err := loadAPINext(t.Context(), root, paths) + if err != nil { + t.Fatal(err) + } + if !maps.Equal(expected.Annotations, annotations) { + t.Errorf("draft annotations differ\nexpected: %v\nactual: %v", expected.Annotations, annotations) + } + + if _, err := os.Stat(filepath.Join(dir, "expected")); err == nil { + bodies := map[string]string{} + for path, text := range actual { + body, ok := strings.CutPrefix(text, generatedHeader) + if !ok { + t.Fatalf("%s: missing generated header", path) + } + bodies[path] = body + } + golden := readTree(t, filepath.Join(dir, "expected")) + for _, path := range sortedKeys(golden, bodies) { + if golden[path] != bodies[path] { + t.Errorf("%s differs from the golden\nexpected:\n%s\nactual:\n%s", path, golden[path], bodies[path]) + } + } + } +} + +func sortedKeys(a, b map[string]string) []string { + keys := maps.Clone(a) + maps.Copy(keys, b) + return slices.Sorted(maps.Keys(keys)) +} diff --git a/cmd/generate-stable-protos/main_test.go b/cmd/generate-stable-protos/main_test.go index cd8d9b7fa..2aa0b7534 100644 --- a/cmd/generate-stable-protos/main_test.go +++ b/cmd/generate-stable-protos/main_test.go @@ -1,106 +1,14 @@ package main import ( - "encoding/json" "io/fs" - "maps" "os" "os/exec" "path/filepath" "reflect" - "strings" "testing" ) -func TestStableProjection(t *testing.T) { - t.Parallel() - for _, fixture := range []string{"classification/valid", "classification/message-types", "imports"} { - t.Run(fixture, func(t *testing.T) { - t.Parallel() - expected := readTree(t, filepath.Join("testdata", fixture, "expected")) - for range 2 { - out := t.TempDir() - if err := stableProtosGenerator(t.Context(), filepath.Join("testdata", fixture, "input"), out); err != nil { - t.Fatal(err) - } - formatTree(t, out) - actual := readTree(t, out) - if !reflect.DeepEqual(expected, actual) { - t.Fatalf("projection differs from independently authored fixture\nexpected: %v\nactual: %v", expected, actual) - } - } - }) - } -} - -func TestAnnotationClassification(t *testing.T) { - t.Parallel() - dirs, err := os.ReadDir("testdata/classification") - if err != nil { - t.Fatal(err) - } - for _, dir := range dirs { - t.Run(dir.Name(), func(t *testing.T) { - t.Parallel() - fixture := filepath.Join("testdata/classification", dir.Name()) - data, err := os.ReadFile(filepath.Join(fixture, "expected.json")) - if err != nil { - t.Fatal(err) - } - var expected struct { - Error string `json:"error"` - Annotations draftAnnotations `json:"annotations"` - } - if err := json.Unmarshal(data, &expected); err != nil { - t.Fatal(err) - } - root := filepath.Join(fixture, "input") - err = stableProtosGenerator(t.Context(), root, t.TempDir()) - if expected.Error == "" { - if err != nil { - t.Fatal(err) - } - paths, err := getAPINextPaths(root) - if err != nil { - t.Fatal(err) - } - _, _, actual, err := loadAPINext(t.Context(), root, paths) - if err != nil { - t.Fatal(err) - } - if !maps.Equal(expected.Annotations, actual) { - t.Fatalf("draft annotations differ\nexpected: %v\nactual: %v", expected.Annotations, actual) - } - return - } - if err == nil || !strings.Contains(err.Error(), expected.Error) { - t.Fatalf("want %q, got %v", expected.Error, err) - } - }) - } -} - -func TestProjectionFailures(t *testing.T) { - t.Parallel() - for _, fixture := range []string{"dangling", "missing"} { - t.Run(fixture, func(t *testing.T) { - t.Parallel() - out := t.TempDir() - sentinel := filepath.Join(out, "retained") - if err := os.WriteFile(sentinel, []byte("old"), 0600); err != nil { - t.Fatal(err) - } - before := readTree(t, out) - if err := stableProtosGenerator(t.Context(), filepath.Join("testdata", fixture, "input"), out); err == nil { - t.Fatal("expected invalid input to fail") - } - if !reflect.DeepEqual(before, readTree(t, out)) { - t.Fatal("generation failure modified output") - } - }) - } -} - func TestRewriteImportPaths(t *testing.T) { t.Parallel() input := `syntax = "proto3"; @@ -185,14 +93,6 @@ exec /bin/mv "$@" } } -func formatTree(t *testing.T, root string) { - t.Helper() - cmd := exec.Command("buf", "format", "-w", root) - if output, err := cmd.CombinedOutput(); err != nil { - t.Fatalf("format: %v: %s", err, output) - } -} - func readTree(t *testing.T, root string) map[string]string { t.Helper() files := map[string]string{} diff --git a/cmd/generate-stable-protos/testdata/classification/message-types/expected/temporal/api/fixture.proto b/cmd/generate-stable-protos/testdata/classification/message-types/expected/temporal/api/fixture.proto index 642d97ba6..444fd3edd 100644 --- a/cmd/generate-stable-protos/testdata/classification/message-types/expected/temporal/api/fixture.proto +++ b/cmd/generate-stable-protos/testdata/classification/message-types/expected/temporal/api/fixture.proto @@ -1,6 +1,3 @@ -// Code generated by generate-stable-protos. DO NOT EDIT. -// @generated - syntax = "proto3"; package fixture; diff --git a/cmd/generate-stable-protos/testdata/classification/message-types/expected/temporal/api/types.proto b/cmd/generate-stable-protos/testdata/classification/message-types/expected/temporal/api/types.proto index 78854f86f..931f0e655 100644 --- a/cmd/generate-stable-protos/testdata/classification/message-types/expected/temporal/api/types.proto +++ b/cmd/generate-stable-protos/testdata/classification/message-types/expected/temporal/api/types.proto @@ -1,6 +1,3 @@ -// Code generated by generate-stable-protos. DO NOT EDIT. -// @generated - syntax = "proto3"; package fixture; diff --git a/cmd/generate-stable-protos/testdata/classification/valid/expected/temporal/api/fixture.proto b/cmd/generate-stable-protos/testdata/classification/valid/expected/temporal/api/fixture.proto index b52868c0c..2c0adb7f4 100644 --- a/cmd/generate-stable-protos/testdata/classification/valid/expected/temporal/api/fixture.proto +++ b/cmd/generate-stable-protos/testdata/classification/valid/expected/temporal/api/fixture.proto @@ -1,6 +1,3 @@ -// Code generated by generate-stable-protos. DO NOT EDIT. -// @generated - syntax = "proto3"; package fixture; diff --git a/cmd/generate-stable-protos/testdata/comments/expected.json b/cmd/generate-stable-protos/testdata/comments/expected.json new file mode 100644 index 000000000..5f0ed611d --- /dev/null +++ b/cmd/generate-stable-protos/testdata/comments/expected.json @@ -0,0 +1,10 @@ +{ + "annotations": { + "fixture.Keeper.b": "b", + "fixture.Keeper.c": "c", + "fixture.Keeper.e": "e", + "fixture.Keeper.f": "f", + "fixture.Keeper.g": "g", + "fixture.Thing": "thing" + } +} diff --git a/cmd/generate-stable-protos/testdata/dangling/expected.json b/cmd/generate-stable-protos/testdata/dangling/expected.json new file mode 100644 index 000000000..451a88a9b --- /dev/null +++ b/cmd/generate-stable-protos/testdata/dangling/expected.json @@ -0,0 +1 @@ +{"error": "cannot find `Missing`"} diff --git a/cmd/generate-stable-protos/testdata/imports/expected.json b/cmd/generate-stable-protos/testdata/imports/expected.json new file mode 100644 index 000000000..e25d2a3bf --- /dev/null +++ b/cmd/generate-stable-protos/testdata/imports/expected.json @@ -0,0 +1,5 @@ +{ + "annotations": { + "fixture.Root.draft": "feature-a" + } +} diff --git a/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/root.proto b/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/root.proto index 07dc23ba0..084261d12 100644 --- a/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/root.proto +++ b/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/root.proto @@ -1,11 +1,7 @@ -// Code generated by generate-stable-protos. DO NOT EDIT. -// @generated - syntax = "proto3"; package fixture; import "temporal/api/used.proto"; - // Keep the literal "temporal/api_next/used.proto" in comments and options. message Root { Used stable = 1 [json_name = "temporal/api_next/used.proto"]; diff --git a/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/unused.proto b/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/unused.proto index 8d1020621..eeeb3e113 100644 --- a/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/unused.proto +++ b/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/unused.proto @@ -1,6 +1,3 @@ -// Code generated by generate-stable-protos. DO NOT EDIT. -// @generated - syntax = "proto3"; package fixture; message Unused {} diff --git a/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/used.proto b/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/used.proto index bf2591135..0cb11575c 100644 --- a/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/used.proto +++ b/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/used.proto @@ -1,6 +1,3 @@ -// Code generated by generate-stable-protos. DO NOT EDIT. -// @generated - syntax = "proto3"; package fixture; message Used {} diff --git a/cmd/generate-stable-protos/testdata/missing/expected.json b/cmd/generate-stable-protos/testdata/missing/expected.json new file mode 100644 index 000000000..fa0da239c --- /dev/null +++ b/cmd/generate-stable-protos/testdata/missing/expected.json @@ -0,0 +1 @@ +{"error": "no such file or directory"} From 5af8d3e3ac126a8e3d331cb2026e86d72dcc30e4 Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Fri, 20 Nov 2026 08:49:36 -0700 Subject: [PATCH 15/18] ci: install protoc for the generate-stable-protos tests What Installs `protoc` in the stable generator CI job using the same setup action as the main CI job. Why The descriptor oracle and breaking-change tests compile protos with `protoc`. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f8573cae3..4f31303ea 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,6 +35,7 @@ jobs: - uses: actions/setup-go@7b8cf10d4e4a01d4992d18a89f4d7dc5a3e6d6f4 # v4.3.0 with: go-version: '^1.25' + - uses: arduino/setup-protoc@a8b67ba40b37d35169e222f3bb352603327985b6 # v2.1.0 - name: Install buf run: make buf-install - name: Test generate-stable From 90633b1bc6a33d5325415d348109722bd212075e Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Sat, 21 Nov 2026 10:10:46 -0700 Subject: [PATCH 16/18] generate-stable-protos: extract commentTokenWords from commentWords What Extracts comment token normalization into `commentTokenWords`. Why Import pruning can reuse the same word parsing when it matches source comments to imports. Co-Authored-By: Claude Opus 5.5 --- cmd/generate-stable-protos/comments.go | 30 +++++++++++++++----------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/cmd/generate-stable-protos/comments.go b/cmd/generate-stable-protos/comments.go index 748195088..c472c55d8 100644 --- a/cmd/generate-stable-protos/comments.go +++ b/cmd/generate-stable-protos/comments.go @@ -134,20 +134,24 @@ func commentWords(stream *token.Stream) map[string]int { if tok.Kind() != token.Comment { continue } - text, block := strings.CutPrefix(tok.Text(), "/*") - if block { - text = strings.TrimSuffix(text, "*/") - } else { - text = strings.TrimPrefix(text, "//") - } - for i, line := range strings.Split(text, "\n") { - if block && i > 0 { - line = strings.TrimPrefix(strings.TrimSpace(line), "*") - } - for _, w := range strings.Fields(line) { - counts[w]++ - } + for _, w := range commentTokenWords(tok.Text()) { + counts[w]++ } } return counts } + +func commentTokenWords(text string) []string { + text, block := strings.CutPrefix(text, "/*") + if !block { + return strings.Fields(strings.TrimPrefix(text, "//")) + } + var words []string + for i, line := range strings.Split(strings.TrimSuffix(text, "*/"), "\n") { + if i > 0 { + line = strings.TrimPrefix(strings.TrimSpace(line), "*") + } + words = append(words, strings.Fields(line)...) + } + return words +} From 19e603fbe7aafa2e09257542a0ed0df42a0e6ea4 Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Fri, 20 Nov 2026 09:26:14 -0700 Subject: [PATCH 17/18] generate-stable-protos: keep the quote style of rewritten import paths What Preserves the original quote style when rewriting temporal import paths. Why The printer sorts by the raw import token, so preserving quotes keeps repeated generation from changing import order. Co-Authored-By: Claude Opus 5.5 --- cmd/generate-stable-protos/main.go | 14 +++++++++++++- cmd/generate-stable-protos/main_test.go | 5 +---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/cmd/generate-stable-protos/main.go b/cmd/generate-stable-protos/main.go index c4a4b1166..cc647934c 100644 --- a/cmd/generate-stable-protos/main.go +++ b/cmd/generate-stable-protos/main.go @@ -342,10 +342,22 @@ func rewriteImportPaths(text string) (string, error) { continue } out.WriteString(text[start:partSpan.Start]) - out.WriteString(strconv.Quote(part.Value[:from] + part.Value[to:])) + out.WriteString(quoteLike(partSpan.Text(), part.Value[:from]+part.Value[to:])) start = partSpan.End } } out.WriteString(text[start:]) return out.String(), nil } + +// quoteLike quotes s with the quote character of the literal it replaces. The printer +// sorts imports by their raw text, so changing the quote would reorder them on the next +// run. +func quoteLike(literal, s string) string { + quoted := strconv.Quote(s) + if !strings.HasPrefix(literal, "'") { + return quoted + } + body := strings.ReplaceAll(quoted[1:len(quoted)-1], `\"`, `"`) + return "'" + strings.ReplaceAll(body, "'", `\'`) + "'" +} diff --git a/cmd/generate-stable-protos/main_test.go b/cmd/generate-stable-protos/main_test.go index 2aa0b7534..505893f3f 100644 --- a/cmd/generate-stable-protos/main_test.go +++ b/cmd/generate-stable-protos/main_test.go @@ -19,7 +19,7 @@ option java_package = "temporal/api_next/used.proto"; // import "temporal/api_next/used.proto"; ` expected := `syntax = "proto3"; -import public /* before */ "temporal/api/used.proto" /* after */; +import public /* before */ 'temporal/api/used.proto' /* after */; import "google/protobuf/any.proto"; import "temporal/api" /* internal comment */ "/another.proto"; option java_package = "temporal/api_next/used.proto"; @@ -32,9 +32,6 @@ option java_package = "temporal/api_next/used.proto"; if actual != expected { t.Fatalf("expected %q, got %q", expected, actual) } - if _, err := rewriteImportPaths(`import "unterminated`); err == nil { - t.Fatal("expected invalid syntax to fail") - } } func TestStableReplacement(t *testing.T) { From 5504bbcc09895e3e3bd334e58bdf2e0a57927a9b Mon Sep 17 00:00:00 2001 From: Stephan Behnke Date: Sat, 21 Nov 2026 10:00:48 -0700 Subject: [PATCH 18/18] README: compile temporal/api or temporal/api_next, never both What Documents compiling one schema tree at a time and checks that each Buf module lists only its own tree. Why The stable and draft trees share protobuf package names, so compiling both produces duplicate symbols. Co-Authored-By: Claude Opus 5.5 --- Makefile | 5 +-- README.md | 7 ++++ cmd/generate-stable-protos/main_test.go | 46 +++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 38977b391..db16f4d2d 100644 --- a/Makefile +++ b/Makefile @@ -53,8 +53,9 @@ stable-api: stable-api-test: printf $(COLOR) "Run generate-stable tests..." @cd cmd/generate-stable-protos/ && go test ./... - printf $(COLOR) "Check that both Buf modules exclude fixture protos..." - files=$$(buf ls-files && buf ls-files --config buf.next.yaml) && ! grep '^cmd/' <<<"$$files" + printf $(COLOR) "Check that each Buf module excludes fixture protos and the other API tree..." + buf ls-files | awk '/^(cmd|temporal\/api_next)\// { print; forbidden = 1 } END { if (forbidden) exit 1 }' + buf ls-files --config buf.next.yaml | awk '/^(cmd|temporal\/api)\// { print; forbidden = 1 } END { if (forbidden) exit 1 }' ##### Compile proto files for go ##### grpc: stable-api buf-lint api-linter resource-id-lint buf-breaking clean go-grpc fix-path diff --git a/README.md b/README.md index 8fe897571..bab1af338 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,13 @@ This repository contains both the protobuf descriptors and OpenAPI documentation Install as git submodule to the project. +## Consumers + +Compile either `temporal/api` (stable) or `temporal/api_next` (preview). Never compile both together. +The trees declare the same proto packages, so compiling both causes duplicate symbols. +The default Buf module in `buf.yaml` excludes `temporal/api_next`. +Use `buf.next.yaml` to compile the preview tree. + ## Contribution Edit proto files under `temporal/api_next/`. Run `make stable-api` to regenerate `temporal/api/`, or run diff --git a/cmd/generate-stable-protos/main_test.go b/cmd/generate-stable-protos/main_test.go index 505893f3f..5907d57ae 100644 --- a/cmd/generate-stable-protos/main_test.go +++ b/cmd/generate-stable-protos/main_test.go @@ -115,3 +115,49 @@ func readTree(t *testing.T, root string) map[string]string { } return files } + +func TestStableAPIBufGuards(t *testing.T) { + t.Parallel() + toolDir := t.TempDir() + for name, script := range map[string]string{ + "go": "exit 0", + "buf": `if [[ "$*" == "ls-files --config buf.next.yaml" ]]; then + printf '%s\n' "$NEXT_FILES" + exit "$NEXT_STATUS" +fi +printf '%s\n' "$DEFAULT_FILES" +exit "$DEFAULT_STATUS"`, + "grep": `if [[ "$FILTER_FAIL" == 1 ]]; then exit 2; fi +exec /usr/bin/grep "$@"`, + "awk": `if [[ "$FILTER_FAIL" == 1 ]]; then exit 2; fi +exec /usr/bin/awk "$@"`, + } { + if err := os.WriteFile(filepath.Join(toolDir, name), []byte("#!/bin/bash\n"+script+"\n"), 0o755); err != nil { + t.Fatal(err) + } + } + for _, tc := range []struct { + name, defaultFiles, nextFiles, defaultStatus, nextStatus, filterFail string + wantFailure bool + }{ + {"clean listings", "temporal/api/service.proto", "temporal/api_next/service.proto", "0", "0", "0", false}, + {"preview file in default listing", "temporal/api_next/service.proto", "", "0", "0", "0", true}, + {"stable file in preview listing", "", "temporal/api/service.proto", "0", "0", "0", true}, + {"fixture in default listing", "cmd/fixture.proto", "", "0", "0", "0", true}, + {"fixture in preview listing", "", "cmd/fixture.proto", "0", "0", "0", true}, + {"default Buf failure", "", "", "2", "0", "0", true}, + {"preview Buf failure", "", "", "0", "2", "0", true}, + {"filter failure", "", "", "0", "0", "1", true}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + cmd := exec.Command("make", "-C", "../..", "stable-api-test", "PATH="+toolDir+string(os.PathListSeparator)+os.Getenv("PATH")) + cmd.Env = append(os.Environ(), "DEFAULT_FILES="+tc.defaultFiles, "NEXT_FILES="+tc.nextFiles, + "DEFAULT_STATUS="+tc.defaultStatus, "NEXT_STATUS="+tc.nextStatus, "FILTER_FAIL="+tc.filterFail) + output, err := cmd.CombinedOutput() + if (err != nil) != tc.wantFailure { + t.Fatalf("want failure %t, got %v\n%s", tc.wantFailure, err, output) + } + }) + } +}