Skip to content

gateway: an offline mark is written only while the record names the stream it ends - #262

Merged
avi-papineni merged 3 commits into
mainfrom
gateway/offline-mark-stream-token
Nov 26, 2026
Merged

avi-papineni merged 3 commits into
mainfrom
gateway/offline-mark-stream-token

Conversation

@avi-papineni

Copy link
Copy Markdown
Contributor

The race

A sync stream's offline mark is written by the replica that served the stream, after the stream has gone. #107 made the registry hold the workload while that mark is written, so a newer stream of the same workload on the same replica registers only after it. Nothing orders one replica's writes against another's:

  1. A stream ends on replica A, and its agent redials through the load balancer to replica B. A directed reconnect makes it redial at once, with no backoff.
  2. B records the new stream PENDING, and SYNCED on its first ack.
  3. A's OFFLINE mark lands after that, and the workload reads offline while B serves its stream. The console shows it offline, and RequestReconnect (Resend snapshot) refuses it, until the next APPLIED ack, which on a quiet workload can be a long time away.

The same happens with one replica whenever two control-plane processes overlap: during a deploy, the outgoing process's GracefulStop ends its streams and writes their offline marks after the agents may already be on the incoming process.

The fix: the offline mark names the stream it ends

  • The token. When a replica registers a stream it gives the stream a random uuid.UUID (uuid.New() in Server.Sync), kept on the in-process session beside the other per-stream state. It is not a timestamp, because two replicas' clocks are not ordered.
  • Where it is written. RecordWorkloadStreamOpen (new, internal/store/queries/workloads.sql) writes the stream's open, sync state PENDING, and sync_stream_id in one statement, so a stream registering replaces the token atomically. Nothing else writes the column. This is the PENDING write a stream already made at open; it moves to directly after sessions.add and runs while the registry holds the workload, the same hold gateway: log every lost reconnect directive; never mark a live stream offline #107 introduced for the offline mark, now also taken for the open record. On one replica, then, the record names streams in the order they registered, and a second stream of the workload registers only once the first one's open is recorded.
  • Why not in RecordAgent. RecordAgent runs at Hello, before the stream is registered. Two streams of one workload on one replica (an agent's deploy turnover) can reach RecordAgent in one order and the registry in the other, or a stream can record its Hello and then fail to register at all. A token written there would then name a stream that is not the registered one, its eventual mark would be skipped, and a workload with no stream would never read offline. Writing the token where the registered stream records its open rules that out.
  • The offline write. MarkWorkloadStreamOffline (new) writes OFFLINE only WHERE sync_stream_id IS NULL OR sync_stream_id = <the ending stream's id>. When the record names another stream, a newer one has registered since, on this replica or another, and the mark writes nothing: registry.Store.MarkStreamOffline reports false with no error, and the gateway logs offline mark not written: a newer sync stream of the workload has opened since this one once at info level, after the write returned. An unknown workload is still ErrWorkloadUnknown.
  • The null case. A row no stream has opened since the migration has a NULL sync_stream_id. A NULL names no stream, so nothing newer is known, and the mark is written exactly as before. Because every stream records its open, and its token, before it can end, a stream served by this release only meets a NULL when its own open write failed (logged as recording stream open).
  • What the token is not. It records which stream of a workload registered last. It does not record whether any stream is alive, nothing reads it to decide liveness, and it is not a presence table. The workload read, the console, and RequestReconnect do not see it; the refusal still mirrors the stored sync state. A replica remembers only the ids of the streams it serves (ADR-0017).

Every writer examined

Writer Where Now
Stream open, PENDING internal/gateway/sync.go Sync, after sessions.add RecordStreamOpen: PENDING plus the stream's id, in one write, under the registry hold. Formerly SetSyncState(PENDING) after the snapshot was queued.
Stream end, OFFLINE (handler exit path) Sync's deferred cleanup MarkStreamOffline, conditioned on the id; a skipped mark is logged at info.
Shutdown (#258) cmd/innerwall/serve.go Unchanged. It writes no state of its own: it ends the streams and waits for their handlers, whose exit path is the row above, so the marks it causes are conditioned too.
Control-plane start cmd/innerwall/serve.go Writes no sync state. It migrates and renders once, which touches workload_policies only. There is no start-up reconciliation that marks workloads offline, so a rolling deploy does not reset the state of streams served elsewhere.
Listener reconnect re-sync Server.Run / reconcile Writes no sync state of its own; a delta it pushes goes through pushLatest, below.
Silence derivation RecordWorkloadFlowReport (ingest) Writes last_flow_report_at and stored gaps, never the sync state.
Retirement RetireWorkload Stamps retired_at; it ends the stream, whose exit path is the conditioned mark.
Delta pushed, PENDING pushLatest Unchanged, unconditioned.
APPLIED / FAILED ack handleAck -> RecordApplied, RecordApplyFailed Unchanged, unconditioned.
Heartbeat, inventory, Hello RecordHeartbeat, RecordFacts, RecordListeningServices, RecordAgent Unchanged.
Snapshot-sent stamp recordSnapshotSent Unchanged.

Why the live-stream writes are left as they are: each runs under its stream's own context, so it can land after a newer stream opened elsewhere only if it was already in flight when its stream ended, a window of one statement. The offline mark was the one write that runs after the stream has gone, by design, and so lands late routinely. Conditioning the ack writes also means telling a skipped write apart from a retired workload in RecordApplied/RecordApplyFailed, which is more than this change needs. The residual windows, and the snapshot-sent stamp (written after its stream may have ended, by design), are recorded in a follow-up issue.

Migration

00019_sync_stream_id.sql: ALTER TABLE workloads ADD COLUMN sync_stream_id uuid, nullable, existing rows NULL; the down migration drops it. No applied migration changes. storetest.Reset's table list is unchanged (a column, not a table), so TestResetTablesAreTheMigratedSchema is unaffected. TestPresentedCredential read the store at migration 00018 after enrolling at 00017; the store's queries are compiled against the latest schema, which now has a column 00018 lacks, so the test now migrates to the latest after enrolling, which still covers a row written before 00018.

The outgoing process of the deploy that brings this release runs the old code, so its marks are still unconditional during that one deploy.

Tests

  • internal/store/sync_stream_test.go TestOfflineMarkNamesItsStream: a row written before 00019 (NULL id) takes the mark as before; a stream open records PENDING and its id; after a newer stream opens and is acked SYNCED, the older stream's mark writes nothing, reports false, and leaves SYNCED and last_seen_at as they were; the newer stream's mark is written; an unknown workload is ErrWorkloadUnknown for both writes.
  • internal/gateway/cross_replica_integration_test.go:
    • TestOfflineMarkFromAnotherReplicaNeverOverwritesNewerStream: two gateways over one database. The stream opens and is acked on A; it ends, and A's mark is held at the registry; the same identity opens on B and reaches PENDING, then SYNCED; A's mark is released. The mark reports not written, the workload reads SYNCED, and RequestReconnect through the fleet domain is accepted and its directive reaches B's stream.
    • TestOfflineMarkWithNoNewerStream: A's stream ends with no newer stream; the mark reports written, the workload reads OFFLINE, and RequestReconnect is refused as offline.
    • Every wait is on a condition with a deadline; the order between the replicas is set by holding A's mark, not by sleeping.
  • internal/gateway/dispatch_test.go TestNewerStreamWaitsForStreamOpenRecord: a stream that has just registered holds its workload until its open is recorded; a second stream registers only after that, and supersedes it.
  • gateway: log every lost reconnect directive; never mark a live stream offline #107's TestOfflineMarkNeverOverwritesNewerStream and TestNewerStreamWaitsForOfflineMark keep their assertions; the first one's delaying store now wraps MarkStreamOffline, which is where the offline mark is written.

The cross-replica test was pushed first, on its own, against the unconditional mark, and CI failed on it; the fix followed in the next commit.

Docs

No change to the proto, the wire contract, the agent, the operator API, or the workload read.

Verified by the project's CI only; nothing was built or run locally.

Fixes #109.


Generated by Claude Code

…n a newer stream

A stream ends on one replica and its agent redials through another,
whose stream reaches SYNCED before the first replica's offline mark is
written. Nothing orders the two replicas' writes, so the test holds the
mark until the newer stream's state is written and releases it then:
the workload must still read SYNCED and a directed reconnect must be
accepted and delivered. A second test ends a stream with no newer one
and expects the mark written and the workload offline.

The first test fails on this commit: the offline mark is unconditional
(issue #109). The fix follows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

No ADR contradictions found (full-corpus audit — the diff touches docs/adr/0018-policy-rendering-and-delta-versioning.md, so every ADR in docs/adr/ was read and the whole record checked, not just the diff).

Scope and what was checked

The PR fixes a cross-replica race (#109) where a sync stream's offline mark, written by the replica that served it after the stream had gone, could land after a newer stream of the same workload had already registered PENDING/SYNCED elsewhere (another replica, or the incoming process of a deploy). The fix adds workloads.sync_stream_id (migration 00019_sync_stream_id.sql): each replica gives a stream a random id when it registers it, writes the id with the stream's PENDING open (RecordStreamOpen), and the offline mark (MarkStreamOffline) is written only while the stored id still names the ending stream or is NULL.

Checked against:

  • ADR-0017 (statelessness, no presence table, Postgres-only durable state) — sync_stream_id is durable state in Postgres, which the record itself requires, not replica-held state. It is not a presence table in the ADR-0017/0005 sense (a workload→replica routing map): nothing reads it to find which replica holds a stream, and the existing notification-channel push/pull mechanism is untouched. It functions only as an optimistic-concurrency token for one replica's own write ordering, and is read back only by the write that wrote it or a later write to the same row — a precedent already established for presented_credential_serial/presented_credential_expires_at (migration 00018), which the new ADR-0018 amendment text cites directly.
  • ADR-0018 decision 3 (rendered state durable, a new stream served the persisted artifact, connecting is not a render trigger) and decision 4 (no presence table, push via notification channel) — both stand unchanged; the amendment only adds which stream the persisted convergence state describes.
  • ADR-0002 / ADR-0015 (no polling, desired-state sync, wire contract) — unaffected; the PR description and the diff confirm no proto, wire-contract, or agent change.
  • ADR-0023 (retirement refused at every door) — unaffected; Sync()'s existing interceptor already refuses a retired identity before RecordStreamOpen/MarkStreamOffline can run, so retirement's guarantees are untouched by this change.
  • ADR-0006 (no ORM, hand-written SQL, sqlc/goose) — the new queries (RecordWorkloadStreamOpen, MarkWorkloadStreamOffline) are hand-written SQL in internal/store/queries/workloads.sql, and the generated Go in internal/store/db/*.go mirrors them with no hand-added logic. The migration (00019_sync_stream_id.sql) is a new file; no applied migration is edited.

The ADR-0018 amendment itself

The amendment to docs/adr/0018-policy-rendering-and-delta-versioning.md follows docs/adr/README.md's in-place-amendment convention:

  • Decision 3's body text is corrected in place (additive sentences appended, not restated) to state which stream the persisted convergence state describes, and is marked *(Amended 2026-11-26; see Amendments.)*.
  • A dated note is added under the existing ## Amendments heading: "2026-11-26 (issue sync state: an offline mark from one replica can overwrite a newer stream's state on another #109): the offline mark names the stream it ends." It states the core decision stands ("so does the absence of a presence table"), explains the reasoning, and is scoped to the one subsidiary point. This matches the pattern of prior entries in this and other ADRs that cite an issue number rather than a PR number (e.g. ADR-0018's own 2026-10-20 entry, ADR-0015's 2026-10-20 entry).
  • No Supersedes: header, no status-line change, and the core decision (render-on-change, diff-based versioning, durable rendered state in Postgres) is untouched — consistent with this being a narrowing/clarification rather than a reversal, so amendment (not supersession) is the correct mechanism.

Document consistency

ARCHITECTURE.md §4.2, docs/troubleshooting.md's "Offline right after Resend snapshot" entry, and the CHANGELOG.md entry all describe the same mechanism as the ADR-0018 amendment and the code change, with no contradictions between them. No dangling ADR/issue/migration references were introduced (migration 00019 follows 00018, the latest on main; ADR-0017, ADR-0018 as amended, and issue #109 all resolve to real content).

Full-corpus check

Read every ADR in docs/adr/ (0001–0023) and docs/adr/README.md. Status lines and Supersedes: headers agree (ADR-0005 Superseded by ADR-0017; ADR-0017 Supersedes: ADR-0005; all others Accepted). Amendment notes elsewhere in the corpus follow the dated-note-under-## Amendments convention this PR's note also follows. CLAUDE.md's hard rules were re-checked against the ADRs they cite (ADR-0002, 0003, 0006, 0007, 0009, 0010, 0011, 0012, 0016, 0017, 0018, 0020, 0021, 0022, 0023) and still match; none of them describe sync_stream_id or are contradicted by it.

… it ends

A sync stream's offline mark is written by the replica that served it,
after the stream has gone. An agent directed to reconnect redials at
once, and its next stream can open on another replica, or on the
incoming process of a deploy while the outgoing one writes the marks of
the streams it ended. Nothing ordered the two processes' writes, so the
old stream's mark could land after the new stream had recorded PENDING
and SYNCED: the workload read offline while its stream was live, and a
directed reconnect was refused, until the next acknowledgement.

A replica now gives each stream it registers a random id. The stream's
open is recorded as PENDING with that id in one statement
(RecordWorkloadStreamOpen, migration 00019), directly after the stream
registers and while the registry holds the workload, the hold #107 took
for the offline mark, so on one replica the record names streams in the
order they registered. The offline mark (MarkWorkloadStreamOffline) is
written only while the record still names the ending stream, or names
none, as a row does that no stream has opened since the migration; when
it names another, the mark writes nothing and the gateway logs that a
newer stream has opened, at info level. The id says which stream
registered last, never whether one is alive, and nothing outside the
gateway reads it.

The writes a live stream makes (pushed deltas, acknowledgements,
heartbeats, inventory, the snapshot stamp) run under the stream's own
context and are unchanged. The shutdown path writes its marks through
the same exit path, and the control plane writes no sync state at
start.

ADR-0018 takes a dated amendment and decision 3 is corrected in place;
ARCHITECTURE.md, the troubleshooting entry, and the changelog follow.
TestPresentedCredential now migrates to the latest schema after
enrolling, since the store's queries read the new column.

Fixes #109.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
Keeps both Unreleased changelog entries.

Signed-off-by: Claude <noreply@anthropic.com>
@avi-papineni
avi-papineni merged commit c681d48 into main Nov 26, 2026
13 checks passed
@avi-papineni
avi-papineni deleted the gateway/offline-mark-stream-token branch November 26, 2026 18:50
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.

sync state: an offline mark from one replica can overwrite a newer stream's state on another

2 participants