From 7048cb2407af58eb71c6a48cd03d5d50e120a82f Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sat, 5 Dec 2026 11:20:39 +0000 Subject: [PATCH] The generated Go wire models carry no digest of the whole registry sdk/go/wire/models.gen.go held one header line with the SHA-256 of the whole registry schema. A change to any model rewrote that line, so two changes to different ops always conflicted on it, and a conflict in a generated file is resolved only by merging and regenerating. Nothing read the line. The check compares the whole generated text, so a stale file still fails. A change to a bound, a default or an enum value that leaves the Go types as they are leaves both generated files unchanged: the Go code is the same. The schema annotation that listed static factory defaults, and the list that classified those factories, only fed the digest and go with it. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/development/code-generation.md | 6 +-- scripts/codegen/sdk_go_gen.py | 35 ++----------- sdk/go/wire/models.gen.go | 1 - tests/unit/test_sdk_go_codegen.py | 78 +++++++++++++++++++++++++---- 4 files changed, 75 insertions(+), 45 deletions(-) diff --git a/docs/development/code-generation.md b/docs/development/code-generation.md index 7fe08a94a2d..7b98ea0c391 100644 --- a/docs/development/code-generation.md +++ b/docs/development/code-generation.md @@ -96,9 +96,9 @@ defaults. Top-level responses include the HTTP fields `ignored_args`, `did_you_mean`, `degraded` and `mirrored` when the server sends them. Go skips other unknown keys when decoding into a struct. -The schema hash tracks literal defaults and static factory defaults. Factories -that compute defaults from other request fields run on the server; the -generator does not hash their behavior. +The files change only with the Go code they hold: a change to a bound, a +default or an enum value that leaves the Go types as they are leaves both +files unchanged. ### sdk_rust_gen diff --git a/scripts/codegen/sdk_go_gen.py b/scripts/codegen/sdk_go_gen.py index 46544b14ba9..854df24c128 100644 --- a/scripts/codegen/sdk_go_gen.py +++ b/scripts/codegen/sdk_go_gen.py @@ -7,8 +7,6 @@ from __future__ import annotations import argparse -import hashlib -import json import re import shutil import subprocess @@ -108,16 +106,6 @@ "working_memory.get": {"block_key": "WithWorkingMemoryGetBlockKey"}, "working_memory.set": {"block_key": "WithWorkingMemorySetBlockKey"}, } -# These factories build constants or copy static collections. -_STATIC_FACTORIES = { - ("CodeBisectCandidatesInput", "wideners"), - ("CodeOutlineInput", "kinds"), - ("CostSummaryInput", "group_by"), - ("InboxRegisterInput", "accept_disclosure"), - ("InspectSettings", "extraction_instructions_refs"), - ("TrackerSimilarInput", "kinds"), - ("WebhookRegisterInput", "events"), -} def _name(wire_name: str) -> str: @@ -141,20 +129,6 @@ def _parameter_name(field: str) -> str: return name if name.isidentifier() and name not in _PARAM_RESERVED else "value" -def _factory_defaults(model: type[BaseModel]) -> dict[str, Any]: - defaults: dict[str, Any] = {} - for name, field in model.model_fields.items(): - factory = field.default_factory - if factory is None or field.default_factory_takes_validated_data: - continue - if factory in (list, dict, set, tuple) or (model.__name__, name) in _STATIC_FACTORIES: - defaults[name] = field.get_default(call_default_factory=True) - elif not (isinstance(factory, type) and issubclass(factory, BaseModel)): - raise ValueError(f"{model.__name__}.{name}: classify the Go schema default factory") - # Nested models have their own schemas; do not run their constructors. - return defaults - - class WireSchema(GenerateJsonSchema): def generate_inner(self, schema: Any) -> JsonSchemaValue: if self.mode == "serialization" and schema["type"] == "model": @@ -185,8 +159,6 @@ def model_schema(self, schema: core_schema.ModelSchema) -> JsonSchemaValue: self.by_alias = by_alias if self.mode == "serialization" and issubclass(model, ProjectedRow): result.pop("required", None) - if defaults := _factory_defaults(model): - result["x-loom-factory-defaults"] = self.encode_default(defaults) if model.__module__ == "server.memory.api.models_conflicts": if field := _UINT64_FIELDS.get(model.__name__): result["properties"][field]["x-loom-go-uint64"] = True @@ -400,11 +372,10 @@ def build_sources() -> tuple[str, str]: if name != emitter.names[key]: decls[name] = f"type {name} = {emitter.names[key]}" - # A bound, static default or enum can change without changing the Go field type. - digest = hashlib.sha256(json.dumps(schema, sort_keys=True).encode()).hexdigest() + # The header holds no digest or count of the registry: such a line changes with + # every model, so two changes to different ops would always conflict on it. parts = [ - "// Code generated by scripts/codegen/sdk_go_gen.py; DO NOT EDIT.\n" - f"// Registry model schema SHA-256: {digest}\n\n" + "// Code generated by scripts/codegen/sdk_go_gen.py; DO NOT EDIT.\n\n" "// Package wire contains the Go requests and responses for Loom operations.\n" "package wire" ] diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 11366cfc44c..7bfb1c964e1 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -1,5 +1,4 @@ // Code generated by scripts/codegen/sdk_go_gen.py; DO NOT EDIT. -// Registry model schema SHA-256: fb4bda5efcd2bd8809de1ec12f6b245c44e018f4624e032e7be186c157f80e10 // Package wire contains the Go requests and responses for Loom operations. package wire diff --git a/tests/unit/test_sdk_go_codegen.py b/tests/unit/test_sdk_go_codegen.py index 86362da618b..b4dbaa445bd 100644 --- a/tests/unit/test_sdk_go_codegen.py +++ b/tests/unit/test_sdk_go_codegen.py @@ -1,8 +1,11 @@ import re +from collections.abc import Callable, Iterator +from contextlib import contextmanager from pathlib import Path import pytest from pydantic import BaseModel, ConfigDict, Field, field_serializer +from pydantic.fields import FieldInfo from pydantic.json_schema import models_json_schema from scripts.codegen import sdk_go_gen @@ -79,20 +82,77 @@ def test_generated_response_retains_http_argument_feedback() -> None: assert 'json:"did_you_mean' not in row_fields -def test_static_factory_default_change_changes_generated_bytes(monkeypatch) -> None: - before = build_source() - field = TrackerSimilarInput.model_fields["kinds"] - request = {"org": "org", "namespace": "ns", "text": "a report"} - assert TrackerSimilarInput.model_validate(request).kinds == ["issue", "pr"] +@contextmanager +def _tracker_similar_with( + monkeypatch: pytest.MonkeyPatch, change: Callable[[pytest.MonkeyPatch], None] +) -> Iterator[None]: + """`change` holds on TrackerSimilarInput and its schema inside the block.""" try: with monkeypatch.context() as patch: - patch.setattr(field, "default_factory", lambda: ["issue"]) + change(patch) TrackerSimilarInput.model_rebuild(force=True) - assert TrackerSimilarInput.model_validate(request).kinds == ["issue"] - after = build_source() + yield finally: TrackerSimilarInput.model_rebuild(force=True) - assert before != after + + +def test_wire_header_holds_no_line_derived_from_the_whole_registry() -> None: + # Fails when the header gains a digest or count of every model: each change to any + # op would rewrite that line, so two such changes could never merge cleanly. + assert build_source().startswith( + "// Code generated by scripts/codegen/sdk_go_gen.py; DO NOT EDIT.\n\n" + "// Package wire contains the Go requests and responses for Loom operations.\n" + "package wire\n\n" + ) + + +def test_bound_change_leaves_generated_sources_identical(monkeypatch: pytest.MonkeyPatch) -> None: + # Fails when any generated line follows a bound: the Go types do not carry one. + before = build_sources() + text = TrackerSimilarInput.model_fields["text"] + bound = Field(max_length=100).metadata + with _tracker_similar_with(monkeypatch, lambda patch: patch.setattr(text, "metadata", bound)): + schema = TrackerSimilarInput.model_json_schema() + assert schema["properties"]["text"]["maxLength"] == 100 + after = build_sources() + assert after == before + + +def test_static_factory_default_change_leaves_generated_sources_identical( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Fails when any generated line follows a default: the server applies request defaults. + before = build_sources() + kinds = TrackerSimilarInput.model_fields["kinds"] + request = {"org": "org", "namespace": "ns", "text": "a report"} + assert TrackerSimilarInput.model_validate(request).kinds == ["issue", "pr"] + with _tracker_similar_with( + monkeypatch, lambda patch: patch.setattr(kinds, "default_factory", lambda: ["issue"]) + ): + assert TrackerSimilarInput.model_validate(request).kinds == ["issue"] + after = build_sources() + assert after == before + + +def test_added_field_changes_only_the_declaration_of_its_model( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Fails when a line outside the changed model's declaration follows the registry. + wire, client = build_sources() + probe = FieldInfo(annotation=str, default="") + with _tracker_similar_with( + monkeypatch, lambda patch: patch.setitem(TrackerSimilarInput.model_fields, "probe", probe) + ): + changed_wire, changed_client = build_sources() + assert changed_client == client # An optional field adds no method and no parameter. + declarations = zip(wire.split("\n\n"), changed_wire.split("\n\n"), strict=True) + changed = [(old, new) for old, new in declarations if old != new] + assert [old.splitlines()[0] for old, _ in changed] == [ + "// TrackerSimilarInput is the request to tracker.similar." + ] + [(before, after)] = changed + lines = before.splitlines() + assert after.splitlines() == [*lines[:-1], 'Probe *string `json:"probe,omitempty"`', "}"] def test_generated_client_binds_each_registered_operation_once() -> None: