Skip to content

AI-3516: finish retried syncs and claims, save configs only over what they read - #2276

Merged
martinmitrevski merged 6 commits into
mainfrom
martinmitrevski/ai-3516-a-retried-sync-or-guest-claim-is
Nov 23, 2026
Merged

martinmitrevski merged 6 commits into
mainfrom
martinmitrevski/ai-3516-a-retried-sync-or-guest-claim-is

Conversation

@martinmitrevski

@martinmitrevski martinmitrevski commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Why

Three writes answered "done" or wrote over somebody else's work (https://linear.app/stream/issue/AI-3516). Each item was checked against main at ce41c39 before it was changed, and all three are real:

  • Sync. syncAgent stored the config with the new sync_hash (internal/api/sync.go:416 on main) before it wrote the skills and simulations. When a skill write failed, the retry found the same hash (sync.go:234) and answered unchanged: true, so the skills were never written.
  • Guest claim. A claim by the account that already holds the guest returned sessions_moved: 0 straight away (internal/api/guests.go:307-311 on main). So a claim that stopped half-way was answered as done on the retry. With shards, the sessions left on a failed shard never moved, although store.ClaimGuest was written to finish them on a retry. Without shards, the account never joined the channels of the conversations it now owns.
  • Config saves. PATCH (config_patch.go:148), PUT (configs.go:253) and sync (sync.go:226) read the config through the one-hour cache, then wrote every column back from that copy (AgentConfigs.Update). Of two saves at once, the later one put back what the earlier had changed. A sync also put back a model the dashboard had just saved, even when agent.yaml does not name a model.

How it works

A save of a stored config is written only over the config it was made from. One that lost a race is made again, whole, on the config as it then is:

PATCH / PUT / sync (onTheConfigAsItIs, at most 5 tries)
└─ one try
   ├─ read the config (maybe cached), apply the request, run every check on the result
   └─ AgentConfigs.Save(config, read = the copy's updated_at, unmodifiedSince = the patch's updated_at)
      BEGIN (detached, as #2209 writes every cached row)
      ├─ SELECT name, connectors, tags, updated_at FOR UPDATE
      ├─ updated_at sent and not the row's ──> ErrAgentConfigChanged ──> 409 conflict
      ├─ the copy's updated_at not the row's ─> ErrStaleAgentConfig, nothing written ──> next try
      ├─ lock bound connections, channel owner, UPDATE every column
      COMMIT, then forget the id and both names (after a refusal too, so the next try reads the row)

So what is stored is always the request applied to the row it replaces, and checked as a whole, the cross-field checks included. Both comparisons are equality at the column's microseconds.

A sync writes its hash last, and only over the config as it left it:

before: config+hash ─> skills ─x   retry: same hash ─> "unchanged", no skills
after:  config, hash "" ─> skills ─> simulations ─> Save(hash, read = this sync's own write)
          (refused as stale when anybody saved in between: the hash stays "", so the next sync writes the directory again)

A guest claim is marked finished after its last step:

claim(guest, account)
├─ claimed by another account ──────────────────> 409, as before
├─ claimed by this account, claim_finished_at set ─> 200, sessions_moved 0, no work (as on main)
└─ unclaimed, or claimed by this account and unfinished (a retry)
   ├─ ClaimGuest: mark, move tasks and sessions (a same-account claim stands)
   ├─ forget the guest in the cache
   ├─ add the account to the moved conversations' channels (failures logged, as before)
   └─ FinishGuestClaim: claim_finished_at = now
Change Result Test that proves it
AgentConfigs.Save (internal/store/agent_config.go), a compare on updated_at under the row lock, used by PATCH, PUT and sync A save made from a copy another save replaced writes nothing TestASaveMadeFromACopyAnotherSaveReplacedWritesNothing
onTheConfigAsItIs (internal/api/configs.go) runs the whole handler again on ErrStaleAgentConfig Saves at once to different fields all land; a request is applied to the row as it is and checked in full TestPatchesAtOnceToDifferentFieldsAllSurvive, TestAPatchIsCheckedAgainstTheConfigAsASaveItsCachedCopyMissedLeftIt, TestAPatchWritesAFieldItSendsThatItsCachedCopyAlreadyHeld, TestAnUpdateWritesAFieldItSendsThatItsCachedCopyAlreadyHeld, TestASyncKeepsAModelSavedSinceItReadTheConfigThatItsDirectoryDoesNotDeclare, TestASyncWritesWhatItsDirectoryDeclaresOverASaveItsCachedCopyMissed
Optional updated_at on AgentConfigPatch, compared for equality A patch made from an older copy gets a 409 conflict, also when a replica's clock was behind. Without the field, nothing changes for the caller TestAPatchMadeFromACopyOlderThanTheConfigIsRefused, TestAPatchSendingTheUpdatedAtItWasLastGivenIsWritten, TestASaveFromACopyOlderThanTheConfigIsRefusedWhenAskedTo, TestASaveIsRefusedOverASaveWhoseClockWasBehind
Sync writes "", then the hash after skills and simulations, only over its own write (sync.go) A sync whose skills failed writes them on the retry; a save between the two writes leaves the hash empty TestASyncWhoseSkillsFailedOnceWritesThemWhenSentAgain, TestASyncLeavesItsHashOffAConfigSavedWhileItWroteItsSkills
users.claim_finished_at (migration 20270201000700), Store.FinishGuestClaim, same-account claim runs every step until it is set (guests.go, store/sessions.go) A retried claim joins the channels and moves what is left; a finished one does nothing again TestAClaimThatStoppedAfterMovingTheRowsJoinsTheChannelsWhenSentAgain, TestAFinishedClaimSentAgainLeavesTheChannelsAsTheyAre, TestAGuestClaimIsFinishedOnlyForTheAccountThatClaimedIt

API behaviour

  • PATCH /v1/agents/configs/{id} takes an optional updated_at. It is enforced only when sent, so existing clients keep working. No client sends it today: JS updateConfig (sdks/js/src/handle.ts:59) and Go UpdateConfig (sdks/go/client/client.go:242) send a patch without it. AgentConfigPatch is additionalProperties: false, so a client that already sent the field would have got a 400. The Volt dashboard is not in this repo, so its save path is unverified. It is compared for equality with the stored updated_at at microseconds, so a GET's microseconds and a PATCH response's nanoseconds both pass.
  • A PATCH, PUT or sync that races another save of the same config is made again on the config as it then is. After 5 lost tries it is answered 409 conflict ("send it again"). Each lost try means another save landed, so 5 saves of one config at once all land.
  • A claim sent again by the same account after it finished answers 200 with sessions_moved: 0 at once, as on main. One that stopped part-way does the remaining work again; sessions_moved counts what that call moved.
  • Migration 20270201000700_guest_claim_finished.sql (global) adds the nullable users.claim_finished_at. Guests claimed before it have none, so the same claim sent again runs its steps once more and is then marked.
  • Regenerated: api/openapi.yaml, the Python client, the JS types and the Go SDK. The Swift --check is unchanged, because both operations are server-side only. The SDK note .claude/skills/sdk/notes/2026-11-23-ai-3516.md lists what .NET, Ruby, Rust and PHP still need.

Judgment calls (please check)

  • "Apply the patch to the locked row." The request is not applied inside the row lock. The checks call out: floorControlComplaint asks the chorus-asr server, regionComplaint asks each router's InRegion and knowledge.Place. Under the lock, in fix(store): write a cached row in a detached transaction and forget what it returned #2209's detached write, they would hold the row lock and a connection across network calls, on a context the request's cancellation does not reach. Instead each try runs the handler on one copy and stores the result only over that same row, so the outcome is the same as applying it to the locked row, with the checks outside it.
  • A sync's retry runs the whole sync again, knowledge included. fillKnowledge skips a document whose text is unchanged, and the page subscriptions and the forget are idempotent, so a lost race costs reads, not re-indexing.
  • "Write the hash last, in the same transaction as the skills." The hash is written last but not in the skills' transaction. The store has no transaction that spans repositories, and the skill and simulation upserts are idempotent, so a retry writes them again. The hash goes in a second Save that is refused as stale if anyone saved the config in between.
  • "Mark the claim done only after its last step." claimed_by is still written first, in the same transaction as the moves (ClaimGuest's doc), or another account could claim the guest in between. claim_finished_at is written after the channel step has run, even when some channels failed: those failures are logged and answered 200, as before, and some never go away (a channel of another app). Re-adding a member already in a channel now happens only for a claim that stopped part-way through its channel step; whether Stream Chat treats that as a no-op is unverified against production (the test runs on the fake).
  • Lock order. Every write of a stored config now locks its row first, then its connections and the channel-owner lock. On main, Update locked the row last. The comments on lockBoundConnections and lockChannelOwner say why no cycle remains: neither a connection delete nor Insert locks a stored config row.
  • Update's query budget goes from 3 to 4: begin, the locked read, the update, commit. Save is the same 4.
  • TestAPatchFromACopyReadBeforeASyncStillHasTheNextSyncWriteAgain from the first version of this PR is gone: it guarded the column merge, which no longer exists.

Validation

Run from acceleration/ at 294648e (on main at ef6b972), against an isolated test database and Redis:

  • go build ./..., go vet (with and without -tags integration) on internal/store and internal/api, gofmt -l: clean
  • go test -count=1 ./internal/store/ ./internal/api/: pass
  • go test -tags integration -p 1 ./internal/api/ (the whole package): pass
  • go test -tags integration -p 1 ./internal/store/ (the whole package, on databases recreated after the rebase): everything passes but TestEveryTableWithAUserIDIsForgottenOrKeptForAReason in both suites. It fails the same way on main at ef6b972: it finds calls.agent_user_id, which nothing here touches. TestEveryHotTableIsReadByIndex/Requests.Insert timed out once reading the shared test Postgres and passed on rerun.
  • go run ./cmd/openapi, go run ./cmd/schema and go generate ./... in sdks/go: nothing left to change. .agents/skills/pr-review/scripts/generated.sh . origin/main: in step. The review fixes do not change openapi.yaml. The Python generator cannot run offline here; run with the cached openapi-python-client 0.29.1 and the main checkout's ruff, it reformats all 518 generated files the same way (imports, Self), so that run was discarded and the two Python files keep the first version's generation.

Each new test was checked to fail without its fix:

Test Fails
TestASyncWritesWhatItsDirectoryDeclaresOverASaveItsCachedCopyMissed on the first version (column merge): Dashboard wording.
TestAPatchIsCheckedAgainstTheConfigAsASaveItsCachedCopyMissedLeftIt on the first version: 200, a text agent stored with a subagent
TestAPatchWritesAFieldItSendsThatItsCachedCopyAlreadyHeld, TestAnUpdateWritesAFieldItSendsThatItsCachedCopyAlreadyHeld on the first version: Be loud.
TestAFinishedClaimSentAgainLeavesTheChannelsAsTheyAre on the first version: the account is back in the channel it left
TestASyncLeavesItsHashOffAConfigSavedWhileItWroteItsSkills with the hash written unconditionally: Should be empty, but was v1. The first version had the condition, so it passes there
TestASaveMadeFromACopyAnotherSaveReplacedWritesNothing with the copy check removed from save
TestASaveIsRefusedOverASaveWhoseClockWasBehind with After in place of Equal
TestAGuestClaimIsFinishedOnlyForTheAccountThatClaimedIt with claimed_by = ? dropped from FinishGuestClaim
The five stale-copy API tests (the four above on configs and sync, and TestASyncKeepsAModelSaved…) with no retry, and with a stale refusal that forgets no cache keys

Checked in the first version of this PR, against main: TestPatchesAtOnceToDifferentFieldsAllSurvive (round 0: instructions lost to a concurrent patch), TestASyncWhoseSkillsFailedOnceWritesThemWhenSentAgain (answered unchanged, no skill), TestASyncKeepsAModelSavedSinceItReadTheConfigThatItsDirectoryDoesNotDeclare (llm went back), TestAClaimThatStoppedAfterMovingTheRowsJoinsTheChannelsWhenSentAgain (not a member), TestAPatchMadeFromACopyOlderThanTheConfigIsRefused and TestAPatchSendingTheUpdatedAtItWasLastGivenIsWritten (400: updated_at unknown).

🤖 Generated with Claude Code

@martinmitrevski martinmitrevski left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewed #2276 at f89cdcb0e in a detached worktree, against base main.

Mergeable: CONFLICTING. acceleration/internal/store/agent_config.go conflicts with #2209 (157ac8c) on main. See the inline comment on save.

CI at this head: CodeQL (actions, python), GitGuardian and labeler passed. Analyze (go) was still pending, and no Go test job ran on this draft.

Every finding has a diff line, so each one is inline: 1 Blocker (sync.go:453), 5 Should fix (sync.go:451, agent_config.go:496, config_patch.go:315, agent_config.go:413, guests.go:311) and 1 Nit (agent_config.go:427).

Tests I ran (integration tests on an isolated database and Redis, -p 1):

  • The PR's new API and store tests pass at the head.
  • I wrote three temporary tests and removed them afterwards. All three fail at the head and pass with the merge base's production files checked out. They back the sync-hash Blocker, the dropped-field comment and the merged-row comment.
  • A mutant with For("UPDATE") removed from save fails TestPatchesAtOnceToDifferentFieldsAllSurvive in round 0, in 3 runs out of 3, so that test does pin the lock.
  • A mutant that writes the hash unconditionally passes all of TestSyncSuite and TestConfigsSuite.

Checked and sound:

  • Lock order. Several other paths lock a config row: refuseDeletedConfig and moveRoom (both FOR SHARE) and Delete (a plain UPDATE). None of them takes a connection, definition or channel-owner lock after it. The connection and definition deletes (DeleteUnbound, softDeleteConnections, ConnectorDefinitions.Delete) only read agent_configs, without locking it. So the order row, then connections, then definitions, then owner lock has no cycle. Two saves that bind one channel connection hold their own rows and then take turns on the advisory lock.
  • Guest claims. A claim by another account is still refused in two places: the handler's check, and claimGuest's WHERE claimed_by IS NULL followed by ErrGuestClaimed. A re-run moves only sessions and tasks still on the guest, so no row is duplicated or moved twice.
  • The empty sync_hash while a sync runs. It is left out of the audit diff (auditBookkeeping). The Go and JS SDKs and the sync itself only check it for equality, so a reader during that window syncs again rather than trusting a hash.
  • The new updated_at field. It has a doc: tag. Its 409 goes through a named errAgentConfigChanged built with conflict(...), and 409 was already in the operation's Errors. generated.sh reports everything in step. The SDK note is its own file in .claude/skills/sdk/notes/, and CHANGELOG.md is not edited.
  • The three TestChannelsSuite failures. They reproduce at the head: the tests expect "the message could not be recorded" and get "something went wrong". They come from #2249, which is in the merge base, and main fixed them in the test-only #2257 (ba73ccc), so a rebase clears them. They are not caused by this PR.

Verdict: request changes, for the sync-hash Blocker on sync.go:453. The merged-row and dropped-field comments have the same cause: columns are merged by comparing with a copy that may be stale. A retry on a changed row would fix all three together.

Comment thread acceleration/internal/api/sync.go Resolved
Comment thread acceleration/internal/api/sync.go Resolved
Comment thread acceleration/internal/api/guests.go Resolved
@martinmitrevski
martinmitrevski force-pushed the martinmitrevski/ai-3516-a-retried-sync-or-guest-claim-is branch from f89cdcb to 294648e Compare November 23, 2026 20:49
@martinmitrevski martinmitrevski changed the title AI-3516: finish retried syncs and claims, merge config saves AI-3516: finish retried syncs and claims, save configs only over what they read Nov 23, 2026

@martinmitrevski martinmitrevski left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Re-reviewed at 294648e36 (rebased onto ef6b9725d). It merges cleanly with current main 9effc9bb0: git merge-tree reports no conflict and GitHub says MERGEABLE. CI: CodeQL passed. The Go, unit and integration jobs were skipped on this draft, so I ran the tests below myself.

All seven findings from the last round are addressed:

  • Blocker, sync hash over a dashboard edit: fixed. My earlier repro now ends with Be brief. and hash v2. The new TestASyncWritesWhatItsDirectoryDeclaresOverASaveItsCachedCopyMissed covers it.
  • Untested hash condition: fixed. A mutant that writes the hash unconditionally now fails TestASyncLeavesItsHashOffAConfigSavedWhileItWroteItsSkills.
  • Merged row nobody checked: fixed. My repro (text agent plus subagent) now gets a 400.
  • Sent field dropped: fixed. My repro now writes Be brief., and PUT is covered too.
  • #2209 conflict: fixed. save runs in detachedWrite, takes its cache keys from the locked read, and also drops the cached copy on a stale refusal, so the retry reads the row as it is.
  • Repeated claim cost: fixed. A finished claim answers 0 at once, and a different account still gets a 409 before that check.
  • Clock comparison: fixed. Both checks now use equality at microsecond precision.

What I checked in the new design:

  • The retry loop is bounded. It makes 5 tries and then returns errAgentConfigBusy, a conflict(...) APIError. PATCH, PUT and sync all declare 409. A try is lost only to a save that committed while it ran, so some save always lands. Each retry runs the read-only checks again (Place and InRegion only read), which is acceptable at this bound. A mutant with configSaveTries = 1 fails six tests.
  • Side effects a sync repeats on retry run at most once in effect. fillKnowledge skips documents already indexed with the same text, and it indexes synchronously. pages.Add upserts the row and de-duplicates the read by asynq task id. forgetKnowledge is idempotent. Skills, simulations and the audit entry come after the save, which is the only step that is retried.
  • Migration 20270201000700. It adds a nullable column with no default, so it does not rewrite the users table, and it sets lock_timeout. It is ordered after main's latest migration, and its down migration loses only the marker. Guests claimed before this deploy have no marker, so the same claim sent again runs its steps once more and then marks it.
  • TestEveryTableWithAUserIDIsForgottenOrKeptForAReason. It only looks for columns named user_id, so the new column cannot affect it. It fails on calls identically at ef6b9725d, and so does TestARenamedModelKeepsItsSKU. Neither comes from this PR.
  • Test runs. All of TestConfigsSuite, TestSyncSuite, TestGuestsSuite and TestChildAgentsSuite pass. The store's agent-config, query-budget and guest-claim tests pass, and so does the sharded claim suite. generated.sh reports everything in step.

No new findings.

Verdict: approve. Posted as a comment because the author is the reviewing account.

martinmitrevski added a commit that referenced this pull request Nov 23, 2026
#2279 (20270201000500) and #2276 (20270201000700) merge first, and goose
refuses a migration older than the newest one applied, so this branch's
migrations move above both: global 20270201001100 (phone_number_orders),
global 20270201001110 (dlc registration requests) and shard
20270201001120 (call_legs_transfer_idx). Nothing else names the versions;
the schema files are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
martinmitrevski added a commit that referenced this pull request Nov 23, 2026
#2279 (20270201000500) and #2276 (20270201000700) merge first, and goose
refuses a migration older than the newest one applied, so this branch's
migrations move above both: global 20270201001100 (phone_number_orders),
global 20270201001110 (dlc registration requests) and shard
20270201001120 (call_legs_transfer_idx). Nothing else names the versions;
the schema files are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
martinmitrevski and others added 5 commits November 23, 2026 22:49
PATCH, PUT and sync read the config through the one-hour cache and wrote
every column back from that copy, so of two saves at once the later put
back what the earlier changed, and a sync put back a model the dashboard
had just saved. AgentConfigs.Save reads the row FOR UPDATE in the
transaction that writes it, and writes only the columns the caller
changed from its copy; every other column keeps the row's value.

A patch may send the updated_at of the copy it was made from. When the
config was saved after it, the patch is refused with a 409. It is
optional, so clients that do not send it are unchanged.

Update goes through the same locked write, so every write of a stored
config locks its row before its connections and channel owner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A sync stored the config with its new hash before it wrote the skills.
When a skill write failed, the retry found the same hash and answered
unchanged, so the skills were never written. The config is now stored
with no hash, and the hash is written once the skills and simulations
are, through a save refused if the config was saved in between.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A claim by the account that already held the guest answered
sessions_moved 0 at once. A claim that stopped half-way was therefore
answered as done on the retry: with shards, sessions left on a failed
shard never moved, and the account never joined the channels of the
conversations it now owns. A same-account claim now runs every step
again. ClaimGuest lets the same account's claim stand with or without
shards, and re-adding a channel member changes nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The first version merged a save onto the locked row column by column,
deciding what changed by comparing with a copy that may have come from
the cache. That kept a stale value the request sent, stored rows no
request had checked as a whole (a text agent with a subagent), and let
a sync write its hash over a dashboard edit it had kept.

AgentConfigs.Save now writes the whole config, under the row lock, only
when the row's updated_at equals the copy's (ErrStaleAgentConfig
otherwise, nothing written, the cached copies forgotten). PATCH, PUT and
sync run again on a stale refusal, at most 5 tries, so what is stored is
the request applied to the row it replaces and checked in full. A
patch's updated_at is compared for equality, not later-than, so a
replica whose clock is behind cannot let a stale patch through. The
sync's hash is written only over its own write.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A claim sent again by the same account ran every step, so a backend
that claims at every sign-in paid two Stream calls per conversation of
the account each time, and put the account back into channels it had
left.

users.claim_finished_at (migration 20270201000700) is set by
Store.FinishGuestClaim after the channel step. The same claim sent again
answers 0 at once once it is set, and runs every step again until then,
so a claim that stopped part-way is still finished by its retry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@martinmitrevski
martinmitrevski force-pushed the martinmitrevski/ai-3516-a-retried-sync-or-guest-claim-is branch from 294648e to 39fe595 Compare November 23, 2026 21:51
@martinmitrevski
martinmitrevski marked this pull request as ready for review November 23, 2026 21:51
The config PATCH took an optional updated_at; the Go, JS and Python
clients were regenerated with it, the other server SDKs' models were
not, so their generate --check failed in CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@martinmitrevski
martinmitrevski merged commit 1029b8d into main Nov 23, 2026
20 checks passed
@martinmitrevski
martinmitrevski deleted the martinmitrevski/ai-3516-a-retried-sync-or-guest-claim-is branch November 23, 2026 22:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant