From ae46b165b5e9b2d886172e38fa8a2caaec8b5497 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Wed, 4 Nov 2026 01:11:37 -0500 Subject: [PATCH] api: the daemon reports a digest of its HTTP contract and the CLI refuses a daemon serving another, naming whether to rebuild the CLI or restart the daemon, instead of failing in whichever response first decodes differently --- cli/cmd/albedo/main.go | 17 +++++- cli/internal/daemon/connection.go | 5 ++ cli/internal/daemon/protocol/api.gen.go | 2 + cli/internal/daemon/protocol/digest.gen.go | 8 +++ cli/internal/daemon/server.go | 26 ++++++++- cli/internal/daemon/server_test.go | 44 ++++++++++++++ cli/tools/apigen/main.go | 68 +++++++++++++++++++--- docs/openapi.yaml | 7 +++ robot-docs/runtime.md | 4 ++ src/albedo/daemon/api_digest.gleam | 5 ++ src/albedo/daemon/server.gleam | 2 + web/src/lib/api.gen.d.ts | 2 + 12 files changed, 177 insertions(+), 13 deletions(-) create mode 100644 cli/internal/daemon/protocol/digest.gen.go create mode 100644 src/albedo/daemon/api_digest.gleam diff --git a/cli/cmd/albedo/main.go b/cli/cmd/albedo/main.go index 1ac33cf9a..d634e49fe 100644 --- a/cli/cmd/albedo/main.go +++ b/cli/cmd/albedo/main.go @@ -42,6 +42,17 @@ func run(args []string) error { var chosen *daemon.Connection var connectMu sync.Mutex acpMode := len(args) > 0 && args[0] == "acp" + // A daemon serving another contract would fail later, in whichever + // response first differs; refuse it here and name the side to update. + checked := func(conn *daemon.Connection, err error) (*daemon.Connection, error) { + if err == nil { + if err = daemon.CheckAPI(conn); err != nil { + conn.HTTPClient().CloseIdleConnections() + return nil, err + } + } + return conn, err + } application := &app.Service{ Connect: func(ctx context.Context) (*daemon.Connection, error) { connectMu.Lock() @@ -59,7 +70,7 @@ func run(args []string) error { } } if found.Kind != localdaemon.Running { - chosen, err = localdaemon.Launch(ctx, options) + chosen, err = checked(localdaemon.Launch(ctx, options)) return chosen, err } // An unknown protocol cannot safely authorize the shutdown operation. @@ -77,10 +88,10 @@ func run(args []string) error { return nil, confirmErr } if restart { - return localdaemon.Upgrade(ctx, options, found.Snapshot) + return checked(localdaemon.Upgrade(ctx, options, found.Snapshot)) } } - chosen, err = localdaemon.AttachOrLaunch(ctx, options, found.Snapshot) + chosen, err = checked(localdaemon.AttachOrLaunch(ctx, options, found.Snapshot)) return chosen, err }, Existing: func(ctx context.Context) (*daemon.Connection, error) { diff --git a/cli/internal/daemon/connection.go b/cli/internal/daemon/connection.go index 7f48ecea4..135510211 100644 --- a/cli/internal/daemon/connection.go +++ b/cli/internal/daemon/connection.go @@ -32,6 +32,7 @@ type Connection struct { type connectionState struct { endpoint ConnectionSnapshot capabilities map[string]int64 + apiDigest string } // Rediscovery obtains an updated endpoint without owning API attachment. @@ -112,6 +113,10 @@ func (c *Connection) Refresh(ctx context.Context) error { return err } defer attached.HTTPClient().CloseIdleConnections() + // A daemon restarted under this client may serve another contract. + if err := CheckAPI(attached); err != nil { + return err + } c.Update(attached) return nil } diff --git a/cli/internal/daemon/protocol/api.gen.go b/cli/internal/daemon/protocol/api.gen.go index 946c01a53..674445344 100644 --- a/cli/internal/daemon/protocol/api.gen.go +++ b/cli/internal/daemon/protocol/api.gen.go @@ -2842,6 +2842,8 @@ type SelectionPatch struct { // Server Examples: {"build":"example-build","capabilities":{"collection_invalidation":1,"durable_inputs":1,"session_replay":1,"storage_report":1,"tool_progress":1},"digest":null,"extensions":[{"name":"work","version":1}],"instance_id":"instance-1","notices":[],"protocol":3,"quota":null,"state":"ready"} type Server struct { + // APIDigest Digest of the HTTP contract this daemon serves (docs/openapi.yaml without prose or examples), as cli/tools/apigen computes it. A client generated from a different digest may reject responses, so it refuses to attach and names the side to rebuild or restart. Absent from daemons that predate it. + APIDigest *string `json:"api_digest,omitempty"` Build *string `json:"build" nullable:"true"` Capabilities map[string]int64 `json:"capabilities"` diff --git a/cli/internal/daemon/protocol/digest.gen.go b/cli/internal/daemon/protocol/digest.gen.go new file mode 100644 index 000000000..2870c058d --- /dev/null +++ b/cli/internal/daemon/protocol/digest.gen.go @@ -0,0 +1,8 @@ +// Code generated by apigen. DO NOT EDIT. + +package protocol + +// APIDigest identifies the wire contract these types were generated from. +// The daemon reports its own in GET /server; a different value means this +// client's decoders may reject what the daemon sends. +const APIDigest = "a24b3bf0b561ac6242b89bb44d571cc61f09c84db2fb2068d84bc90d807f7334" diff --git a/cli/internal/daemon/server.go b/cli/internal/daemon/server.go index 353e1ae50..03a729b82 100644 --- a/cli/internal/daemon/server.go +++ b/cli/internal/daemon/server.go @@ -24,6 +24,7 @@ type ServerInfo struct { Capabilities map[string]int64 Build string Digest string + APIDigest string Notices []ServerNotice } type ServerNotice struct{ ID, Kind, Message string } @@ -37,7 +38,7 @@ func decodeServer(body []byte) (ServerInfo, error) { if server.InstanceID == "" || server.Protocol <= 0 || server.Capabilities == nil || (server.State != "ready" && server.State != "draining") { return ServerInfo{}, &ProtocolError{Code: "invalid_server", Operation: "read server", Cause: errors.New("missing daemon identity, protocol, state, or capabilities")} } - return ServerInfo{State: server.State, Protocol: int(server.Protocol), InstanceID: server.InstanceID, Capabilities: server.Capabilities, Build: value(server.Build), Digest: value(server.Digest), Notices: noticeValues(server.Notices)}, nil + return ServerInfo{State: server.State, Protocol: int(server.Protocol), InstanceID: server.InstanceID, Capabilities: server.Capabilities, Build: value(server.Build), Digest: value(server.Digest), APIDigest: value(server.APIDigest), Notices: noticeValues(server.Notices)}, nil } @@ -91,11 +92,32 @@ func Attach(ctx context.Context, snapshot ConnectionSnapshot, rediscover Redisco return nil, err } snapshot.Version, snapshot.Build, snapshot.Digest, snapshot.InstanceID = server.Protocol, server.Build, server.Digest, server.InstanceID - conn.state.Store(&connectionState{endpoint: snapshot, capabilities: maps.Clone(server.Capabilities)}) + conn.state.Store(&connectionState{endpoint: snapshot, capabilities: maps.Clone(server.Capabilities), apiDigest: server.APIDigest}) return conn, nil } +// APIMismatchError names a daemon serving a different HTTP contract than the +// one this client was generated from, whose responses its decoders may reject. +type APIMismatchError struct{ Daemon, Client string } + +func (e *APIMismatchError) Error() string { + return fmt.Sprintf("the running daemon serves a different API than this albedo CLI was built for (daemon %.12s, CLI %.12s). "+ + "If the CLI is the older one, rebuild it from the daemon's checkout (go -C cli install ./cmd/albedo); "+ + "if the daemon is, restart it (albedo daemon --stop, then run albedo again)", e.Daemon, e.Client) +} + +// CheckAPI refuses an attached daemon that reports another contract digest. +// Daemons that predate the digest report none and are not refused. Stopping a +// daemon does not need it, so only connections that use the API check. +func CheckAPI(conn *Connection) error { + state := conn.state.Load() + if state == nil || state.apiDigest == "" || state.apiDigest == protocol.APIDigest { + return nil + } + return &APIMismatchError{Daemon: state.apiDigest, Client: protocol.APIDigest} +} + // StopDaemon drains the daemon. Its kernels keep running for the next daemon // unless stopKernels ends them too. func StopDaemon(ctx context.Context, conn *Connection, stopKernels bool) error { diff --git a/cli/internal/daemon/server_test.go b/cli/internal/daemon/server_test.go index 047bbc37b..b83cf36b5 100644 --- a/cli/internal/daemon/server_test.go +++ b/cli/internal/daemon/server_test.go @@ -10,9 +10,12 @@ import ( "net" "net/http" "net/http/httptest" + "strings" "sync/atomic" "testing" "time" + + "albedo/cli/internal/daemon/protocol" ) const readyServer = `{"instance_id":"instance-a","protocol":3,"state":"ready","capabilities":{"durable_inputs":1,"session_replay":2,"collection_invalidation":1,"tool_progress":1},"build":"verified-build","digest":"verified-digest","extensions":[],"quota":[],"notices":[]}` @@ -326,3 +329,44 @@ func TestBuildMismatchStaysQuietOnlyForProvenSameness(t *testing.T) { } } } + +// A daemon from another contract still attaches, so `albedo daemon --stop` +// can reach it, but CheckAPI and a refresh onto it refuse it by name instead +// of failing in whichever response first decodes differently. +func TestCheckAPIRefusesAnotherContractButNotAnUnreportedOne(t *testing.T) { + for _, change := range []struct { + name string + digest any + refused bool + }{ + {"same contract", protocol.APIDigest, false}, + {"daemon predates the digest", nil, false}, + {"other contract", strings.Repeat("0", 64), true}, + } { + t.Run(change.name, func(t *testing.T) { + var resource map[string]any + _ = json.Unmarshal([]byte(readyServer), &resource) + if change.digest != nil { + resource["api_digest"] = change.digest + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(resource) + })) + defer server.Close() + snapshot := ConnectionSnapshot{Port: server.Listener.Addr().(*net.TCPAddr).Port, Token: "token"} + conn, err := Attach(t.Context(), snapshot, func(context.Context) (ConnectionSnapshot, error) { return snapshot, nil }) + if err != nil { + t.Fatalf("attach for stopping refused: %v", err) + } + for _, step := range []struct { + name string + err error + }{{"check", CheckAPI(conn)}, {"refresh", conn.Refresh(t.Context())}} { + _, mismatch := errors.AsType[*APIMismatchError](step.err) + if mismatch != change.refused || (!change.refused && step.err != nil) { + t.Fatalf("%s: refused=%v, want %v (%v)", step.name, mismatch, change.refused, step.err) + } + } + }) + } +} diff --git a/cli/tools/apigen/main.go b/cli/tools/apigen/main.go index 9c3bb8821..2c9f37938 100644 --- a/cli/tools/apigen/main.go +++ b/cli/tools/apigen/main.go @@ -3,6 +3,8 @@ package main import ( "bytes" + "crypto/sha256" + "encoding/hex" "encoding/json" "flag" "fmt" @@ -35,6 +37,10 @@ func generate(check bool) error { if err := yaml.Unmarshal(data, &document); err != nil { return err } + digest, err := contractDigest(data) + if err != nil { + return err + } // oapi-codegen supports 3.1. SSE item schemas stay in the canonical 3.2 // document; the adapter owns framing, delivery and cursor recovery. document["openapi"] = "3.1.0" @@ -72,18 +78,64 @@ func generate(check bool) error { if err != nil { return err } - target := filepath.Join(root, "cli", "internal", "daemon", "protocol", "api.gen.go") - if check { - current, err := os.ReadFile(target) - if err != nil { + outputs := []struct{ path, content string }{ + {filepath.Join(root, "cli", "internal", "daemon", "protocol", "api.gen.go"), source}, + {filepath.Join(root, "cli", "internal", "daemon", "protocol", "digest.gen.go"), "// Code generated by apigen. DO NOT EDIT.\n\npackage protocol\n\n// APIDigest identifies the wire contract these types were generated from.\n// The daemon reports its own in GET /server; a different value means this\n// client's decoders may reject what the daemon sends.\nconst APIDigest = \"" + digest + "\"\n"}, + {filepath.Join(root, "src", "albedo", "daemon", "api_digest.gleam"), "//// Generated by cli/tools/apigen from docs/openapi.yaml. Do not edit.\n//// GET /server reports it so a client built from another contract can tell.\n\npub const digest =\n \"" + digest + "\"\n"}, + } + for _, output := range outputs { + if check { + current, err := os.ReadFile(output.path) + if err != nil { + return err + } + if !bytes.Equal(current, []byte(output.content)) { + return fmt.Errorf("generated API is stale (%s); run go generate ./internal/daemon", output.path) + } + } else if err := os.WriteFile(output.path, []byte(output.content), 0644); err != nil { return err } - if !bytes.Equal(current, []byte(source)) { - return fmt.Errorf("generated API is stale; run go generate ./internal/daemon") + } + return nil +} + +// contractDigest hashes the contract as authored, without the prose and +// examples, so rewording a description does not split clients from daemons +// while any change to a shape, a required set or a route does. +func contractDigest(data []byte) (string, error) { + var document any + if err := yaml.Unmarshal(data, &document); err != nil { + return "", err + } + canonical, err := json.Marshal(withoutProse(document, false)) + if err != nil { + return "", err + } + sum := sha256.Sum256(canonical) + return hex.EncodeToString(sum[:]), nil +} + +// withoutProse drops documentation keywords. Inside a properties map the keys +// are field names, so a field called description stays. +func withoutProse(value any, names bool) any { + switch node := value.(type) { + case []any: + result := make([]any, len(node)) + for index, child := range node { + result[index] = withoutProse(child, false) + } + return result + case map[string]any: + result := make(map[string]any, len(node)) + for key, child := range node { + if !names && (key == "description" || key == "summary" || key == "example" || key == "examples") { + continue + } + result[key] = withoutProse(child, !names && key == "properties") } - return nil + return result } - return os.WriteFile(target, []byte(source), 0644) + return value } // project selects Go representations without changing the wire contract. diff --git a/docs/openapi.yaml b/docs/openapi.yaml index bb1f37af7..63ff79cc7 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -6270,6 +6270,13 @@ components: type: [string, 'null'] pattern: ^[0-9a-f]{64}$ description: Content digest of the running code tree; update information, not attachment compatibility. + api_digest: + type: string + pattern: ^[0-9a-f]{64}$ + description: Digest of the HTTP contract this daemon serves (docs/openapi.yaml without prose or + examples), as cli/tools/apigen computes it. A client generated from a different digest may reject + responses, so it refuses to attach and names the side to rebuild or restart. Absent from daemons + that predate it. extensions: type: array items: diff --git a/robot-docs/runtime.md b/robot-docs/runtime.md index ba9503d01..ad98ec264 100644 --- a/robot-docs/runtime.md +++ b/robot-docs/runtime.md @@ -380,3 +380,7 @@ runtimes work too. Never replace readiness with a sleep or bounded polling. ## HTTP route inventory `test/harness/http_routes_test.py` compares daemon and extension dispatch arms with `docs/openapi.yaml` operations without booting a daemon. It normalizes parameter names and checks method/path pairs in both directions. It reads outer dispatch arms in the current Gleam layout and the OpenAPI path/operation indentation; new routing syntax needs an extractor update. The Go E2E contract transport checks response schemas for requests it exercises, and `test.sh` separately checks generated Go bindings with `apigen -check`. + +## Contract digest + +The CLI's decoders are generated from `docs/openapi.yaml` and reject responses that miss a field they require, so a CLI built from one revision cannot use a daemon serving another: a `go install`ed CLI next to a checkout whose daemon `gleam run` rebuilds after every pull, or a new package beside a daemon whose restart was declined. `apigen` hashes the contract without its prose (`description`, `summary`, `example`, `examples`) and writes the same value to `cli/internal/daemon/protocol/digest.gen.go` and `src/albedo/daemon/api_digest.gleam`; `apigen -check` keeps both current. `GET /server` reports it as `api_digest`. `daemon.Attach` still accepts a daemon with another digest, so `albedo daemon --stop` reaches it, but the CLI's `Connect` and `Connection.Refresh` refuse it with `APIMismatchError`, which names both remedies (rebuild the CLI, or restart the daemon). A daemon that reports no digest predates it and is not refused. Rewording docs leaves the digest alone; any change to a shape, a required set or a route changes it, compatible or not, so after such a change a CLI and daemon must come from the same revision. diff --git a/src/albedo/daemon/api_digest.gleam b/src/albedo/daemon/api_digest.gleam new file mode 100644 index 000000000..8ba1984a3 --- /dev/null +++ b/src/albedo/daemon/api_digest.gleam @@ -0,0 +1,5 @@ +//// Generated by cli/tools/apigen from docs/openapi.yaml. Do not edit. +//// GET /server reports it so a client built from another contract can tell. + +pub const digest = + "a24b3bf0b561ac6242b89bb44d571cc61f09c84db2fb2068d84bc90d807f7334" diff --git a/src/albedo/daemon/server.gleam b/src/albedo/daemon/server.gleam index 1d8acc360..929b05bd5 100644 --- a/src/albedo/daemon/server.gleam +++ b/src/albedo/daemon/server.gleam @@ -1,6 +1,7 @@ import albedo/clock import albedo/daemon/acp_attachments import albedo/daemon/active_output +import albedo/daemon/api_digest import albedo/daemon/configuration import albedo/daemon/http_acp import albedo/daemon/http_active_output @@ -1071,6 +1072,7 @@ fn protocol_server( let fields = [ #("instance_id", json.string(instance_id)), #("protocol", json.int(3)), + #("api_digest", json.string(api_digest.digest)), #("state", json.string("ready")), #( "capabilities", diff --git a/web/src/lib/api.gen.d.ts b/web/src/lib/api.gen.d.ts index fec87b97a..0c2ff2b99 100644 --- a/web/src/lib/api.gen.d.ts +++ b/web/src/lib/api.gen.d.ts @@ -1795,6 +1795,8 @@ export interface components { build: string | null; /** @description Content digest of the running code tree; update information, not attachment compatibility. */ digest: string | null; + /** @description Digest of the HTTP contract this daemon serves (docs/openapi.yaml without prose or examples), as cli/tools/apigen computes it. A client generated from a different digest may reject responses, so it refuses to attach and names the side to rebuild or restart. Absent from daemons that predate it. */ + api_digest?: string; extensions: { name: components["schemas"]["ID"]; version: number; -- knotmirror 0.0.1