Skip to content

feat(engine,server): durable run identity — a host-minted run_id - #827

Merged
samuv merged 1 commit into
sdk/03-corsfrom
sdk/04-run-id
Aug 31, 2026
Merged

samuv merged 1 commit into
sdk/03-corsfrom
sdk/04-run-id

Conversation

@samuv

@samuv samuv commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #826 → #825 → #823 → #822. Review those first.

What

PR 4 of 9 in the #821 server-enabler stack. Implements Scenario 4 — AC4.1–AC4.8 — per ADR 0245.

Gives every run an opaque, host-minted identity that survives restart.

Why this is a bug fix, not just SDK plumbing

mecatl had no way to name a run. A run was identified only by being the live run of a session, and Event.Seq is monotonic within a run and restarts each run — so it cannot tell two runs of one session apart.

That's fine for one client holding one bidi stream (mecatui). It breaks the moment a second client attaches or the same client reconnects: approve ask X and cancel are addressed to the session, so a control in flight while a run ends lands on whatever started next. That's a live correctness bug, not only an ergonomics gap.

The loop stamps the id — a corrected ADR decision

ADR 0245 originally said stamp at "the single relay chokepoint, Actor-style". That decision was corrected in the preceding commit, before the record froze, because no such chokepoint exists:

  • Service.relayEvent takes session.Event by value — it cannot mutate the copy its caller hands to toProto.
  • Five further recorder.Observe sites bypass it entirely.
  • Actor gets away with it by being log-only — persistence really does have one chokepoint in appendEvent. run_id must also reach the client wire, which never passes through it.

Stamping "at the relay" meant ~9 hand-maintained sites: the per-surface drift class AGENTS.md records as having fired three times already.

So it's stamped at Run.emit/emitOrAbort, beside the existing ev.Seq = r.seq.Add(1). Those two functions are the only places a run hands an event outward, which makes the guarantee structural rather than diligent. The objection that keeps Actor out of the loop doesn't transfer — the loop knows nothing about principals, but the run is its own concept.

One host field, two effects

RunRequest.RunID stamps events and, when AskIDDiscriminator is empty, supplies the ask discriminator. That's the arrangement ADR 0044 described in terms of a run id that didn't then exist — "a durable host passes its own RunID". Nothing in the repo had ever set that seam, so the property was theoretical; it's now load-bearing.

Precedence lives in askDiscriminatorFor, extracted as a free function specifically so it's testable without launching a run goroutine. An explicit AskIDDiscriminator still wins — the derivation is a default, not a constraint.

Resume continues, prompt mints

Seam Action
StartRunContent (prompt, retry, scheduler fires, steer promotion) mint, stamped on the aggregate before launch so it's on the snapshot the moment the run can park awaiting
ResumeApproval reuse — reads it back off the session
ApprovePlan no code at all — routes through resumeFromAwaiting then StartRunContent, so reuse-then-mint composes for free

The session fallback is confined to the resume seam on purpose: a prompt entry must never read the id off the session, because a reused session still carries the id of the run that just ended. AC4.5's test verifies the plan composition rather than assuming it.

Empty is a meaning, not a gap

An empty RunID marks an event session-scoped rather than run-scoped. The scheduler's three schedule.* events are emitted from composition outside any loop and genuinely have no run — manufacturing one would be a lie that later reads as truth.

The permitted set is closed and gated, in the harnessTokenFields idiom. The gate's failure message states the consequence a reviewer must weigh, because it's otherwise invisible: an attachment filters to one run and will never deliver a new run-less type; only a session activity stream will. That asymmetry is why attach() and activity() are separate operations.

Two guards caught real defects

  1. TestToProtoStructuralUTF8Guard flagged Event.run_id. I'd written that the field is harness-minted and needs no repair. True of this binary, false of the contract: engine/agent is an importable library and RunRequest.RunID is public, so an embedder can supply arbitrary bytes — and invalid UTF-8 in a proto string is codes.Internal on a live stream (issue Normalize invalid UTF-8 tool output before protobuf streaming #402). Now goes through valid().
  2. task api:check flagged all four additions, which is exactly its job.

Engine API

session.Event.RunID, session.Session.BeginRun/RunID, agent.RunRequest.RunID, sessnap.Snapshot.RunID — all Added = minor, with api:update output and a changelog entry. Proto Event.run_id = 22.

No behaviour change when unset: a host supplying no RunID emits an empty one and asks fall back to the process-global serial, byte-identical to before. A legacy snapshot restores empty and heals on its next run — no migration sweep.

Acceptance criteria

AC Test
4.1 one id per run, distinct across runs TestSDKServerEnablers_Scenario4_EveryRunEventCarriesOneID
4.2 run id supplies the ask discriminator TestADR_0245_RunIDIsTheAskDiscriminator
4.3 loop stamps every emitted event TestADR_0245_LoopStampsEveryEmittedEvent
4.4 awaiting resume keeps the id TestADR_0245_AwaitingResumeKeepsRunID
4.5 plan resolution spans two ids TestSDKServerEnablers_Scenario4_PlanResolutionSpansTwoRunIDs
4.6 run-less set is closed TestADR_0245_RunlessEventSetIsClosed
4.7 fold ignores RunID TestADR_0245_FoldIgnoresRunID
4.8 legacy snapshot restores empty TestSDKServerEnablers_Scenario4_LegacySnapshotRestoresEmpty
— mint properties TestADR_0245_MintedRunIDsAreOpaqueUniqueAndColonFree

Verification

task lint 0 issues all modules · task api:check green · go test -race ./... green on root and engine · docs/lint green · mecademo prints a full offline session.

One flake seen and chased down: TestCallerSeparation_Scenario4_OwnerlessCutoverIsObservableAndSafe failed once under the full parallel -race ./... with storage health unavailable, alongside redis: dial tcp 127.0.0.1:50444: connection refused noise. It passes 3/3 in isolation and the whole internal/app package passes under -race; it's miniredis port contention in storage code this PR doesn't touch. Flagging rather than burying it.

Refs #821.

🤖 Generated with Claude Code

@jhrozek jhrozek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed against ADR 0245, which #822 raised a specific concern about: RunID uniqueness was previously going to be caller-trusted, threatening the CWE-863 askID replay guard. Verified directly in the code — runid.go mints via crypto/rand (128 bits), one call site, and the loop only ever reads r.runID at the two documented stamp sites (grepped engine/agent/*.go to confirm). Session.BeginRun/RunID are proper aggregate methods, sessnap persistence matches the Profile/ProviderID precedent, resume-vs-mint seam separation is correctly tested. No issues — approving.

PR 4 of the #821 server-enabler stack. Implements Scenario 4 of
docs/acceptance/sdk-server-enablers.md (AC4.1-AC4.8) per ADR 0245.

mecatl had no way to name a run. A run was identified only by BEING the live
run of a session, and Event.Seq is monotonic WITHIN a run and restarts every
run, so it cannot tell two runs of one session apart. That is fine for one
client holding one bidi stream (mecatui) and breaks the moment a second
client attaches or the same client reconnects: "approve ask X" and "cancel"
are addressed to the SESSION, so a control in flight while a run ends lands
on whatever started next. That is a correctness bug today, not only an SDK
ergonomics gap.

THE LOOP STAMPS THE ID. ADR 0245 originally said stamp it at "the single
relay chokepoint, Actor-style"; that decision was corrected before the record
froze (see the preceding commit) because no such chokepoint exists.
Service.relayEvent takes session.Event BY VALUE so it cannot mutate the copy
its caller hands to toProto, and five further recorder.Observe sites bypass
it entirely. Actor gets away with it by being LOG-ONLY — persistence really
does have one chokepoint in appendEvent — but run_id must also reach the
client wire, which never passes through it. Stamping "at the relay" meant
~9 hand-maintained sites: the per-surface drift class AGENTS.md records as
having fired three times already.

So it is stamped at Run.emit/emitOrAbort, beside the existing
ev.Seq = r.seq.Add(1). Those two functions are the only places a run hands an
event outward, which makes the guarantee structural rather than diligent. The
semantic objection that keeps Actor out of the loop does not transfer: the
loop knows nothing about principals, but the run is its OWN concept.

ONE HOST FIELD, TWO EFFECTS. RunRequest.RunID stamps events AND — when
AskIDDiscriminator is empty — supplies the ask discriminator, which is the
arrangement ADR 0044 described in terms of a run id that did not then exist
("a durable host passes its own RunID"). Nothing in the repo had ever set
that seam, so the property was theoretical; it is now load-bearing. The
precedence lives in askDiscriminatorFor, extracted as a free function
specifically so it is testable without launching a run goroutine. An explicit
AskIDDiscriminator still wins, so the derivation is a default, not a
constraint.

RESUME CONTINUES, PROMPT MINTS. StartRunContent mints and stamps the
aggregate BEFORE launching, so the id is on the snapshot the moment the run
can park awaiting. ResumeApproval reads it back off the session. The fallback
is confined to that seam on purpose: a prompt entry must never read the id
off the session, because a reused session still carries the id of the run
that just ended. ApprovePlan needed no code at all — it routes through
resumeFromAwaiting then StartRunContent, so reuse-then-mint composes for
free, which the AC4.5 test verifies rather than assumes.

EMPTY IS A MEANING. An empty RunID marks an event session-scoped rather than
run-scoped; the scheduler's three schedule.* events are emitted from
composition outside any loop and genuinely have no run. The permitted set is
CLOSED and gated, in the harnessTokenFields idiom — and the gate's failure
message states the consequence a reviewer must weigh, because it is otherwise
invisible: an attachment filters to one run and will NEVER deliver a new
run-less type, while a session activity stream will.

Run ids are 128 random bits, unpadded lowercase base32, "run_"-prefixed.
Colon-free because they feed the askID grammar; opaque because a client that
can parse structure out of an id will come to depend on it. Uniqueness backs
the CWE-863 replay guard across processes and restarts, which a process-local
counter cannot promise.

Two guards caught real defects during this change:

  - TestToProtoStructuralUTF8Guard flagged Event.run_id. I had written that
    the field is harness-minted and needs no repair. That is true of this
    binary and FALSE of the contract: engine/agent is an importable library
    and RunRequest.RunID is public, so an embedder can supply arbitrary
    bytes, and invalid UTF-8 in a proto string is codes.Internal on a live
    stream (issue #402). It now goes through valid().
  - task api:check flagged all four additions, which is exactly its job.

Engine API: session.Event.RunID, session.Session.BeginRun/RunID,
agent.RunRequest.RunID, sessnap.Snapshot.RunID — all Added/minor, with
api:update output and an engine/CHANGELOG.md entry. Proto Event.run_id = 22.
No behaviour change when unset: a host supplying no RunID emits an empty one
and asks fall back to the process-global serial, byte-identical to before.

Gates: task lint 0 issues all modules; task api:check green; go test -race
green on root and engine; docs/lint green; mecademo prints a full offline
session.

Refs #821.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
@samuv
samuv merged commit 447d3e1 into main Aug 31, 2026
8 of 29 checks passed
@samuv
samuv deleted the sdk/04-run-id branch August 31, 2026 10:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants