Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions docs/development/code-generation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
35 changes: 3 additions & 32 deletions scripts/codegen/sdk_go_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
from __future__ import annotations

import argparse
import hashlib
import json
import re
import shutil
import subprocess
Expand Down Expand Up @@ -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:
Expand All @@ -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":
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"
]
Expand Down
1 change: 0 additions & 1 deletion sdk/go/wire/models.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

78 changes: 69 additions & 9 deletions tests/unit/test_sdk_go_codegen.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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:
Expand Down
Loading