Repository navigation
AI-3516: finish retried syncs and claims, save configs only over what they read - #2276
Conversation
martinmitrevski
left a comment
There was a problem hiding this comment.
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 fromsavefailsTestPatchesAtOnceToDifferentFieldsAllSurvivein 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
TestSyncSuiteandTestConfigsSuite.
Checked and sound:
- Lock order. Several other paths lock a config row:
refuseDeletedConfigandmoveRoom(bothFOR SHARE) andDelete(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 readagent_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'sWHERE claimed_by IS NULLfollowed byErrGuestClaimed. A re-run moves only sessions and tasks still on the guest, so no row is duplicated or moved twice. - The empty
sync_hashwhile 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_atfield. It has adoc:tag. Its 409 goes through a namederrAgentConfigChangedbuilt withconflict(...), and 409 was already in the operation'sErrors.generated.shreports everything in step. The SDK note is its own file in.claude/skills/sdk/notes/, andCHANGELOG.mdis not edited. - The three
TestChannelsSuitefailures. 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.
f89cdcb to
294648e
Compare
martinmitrevski
left a comment
There was a problem hiding this comment.
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 hashv2. The newTestASyncWritesWhatItsDirectoryDeclaresOverASaveItsCachedCopyMissedcovers 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.
saveruns indetachedWrite, 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, aconflict(...)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 (PlaceandInRegiononly read), which is acceptable at this bound. A mutant withconfigSaveTries = 1fails six tests. - Side effects a sync repeats on retry run at most once in effect.
fillKnowledgeskips documents already indexed with the same text, and it indexes synchronously.pages.Addupserts the row and de-duplicates the read by asynq task id.forgetKnowledgeis 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 theuserstable, and it setslock_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 nameduser_id, so the new column cannot affect it. It fails oncallsidentically atef6b9725d, and so doesTestARenamedModelKeepsItsSKU. Neither comes from this PR.- Test runs. All of
TestConfigsSuite,TestSyncSuite,TestGuestsSuiteandTestChildAgentsSuitepass. The store's agent-config, query-budget and guest-claim tests pass, and so does the sharded claim suite.generated.shreports everything in step.
No new findings.
Verdict: approve. Posted as a comment because the author is the reviewing account.
#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>
#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>
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>
294648e to
39fe595
Compare
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>
Why
Three writes answered "done" or wrote over somebody else's work (https://linear.app/stream/issue/AI-3516). Each item was checked against
mainat ce41c39 before it was changed, and all three are real:syncAgentstored the config with the newsync_hash(internal/api/sync.go:416on main) before it wrote the skills and simulations. When a skill write failed, the retry found the same hash (sync.go:234) and answeredunchanged: true, so the skills were never written.sessions_moved: 0straight away (internal/api/guests.go:307-311on 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, althoughstore.ClaimGuestwas written to finish them on a retry. Without shards, the account never joined the channels of the conversations it now owns.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 whenagent.yamldoes 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:
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:
A guest claim is marked finished after its last step:
AgentConfigs.Save(internal/store/agent_config.go), a compare onupdated_atunder the row lock, used by PATCH, PUT and syncTestASaveMadeFromACopyAnotherSaveReplacedWritesNothingonTheConfigAsItIs(internal/api/configs.go) runs the whole handler again onErrStaleAgentConfigTestPatchesAtOnceToDifferentFieldsAllSurvive,TestAPatchIsCheckedAgainstTheConfigAsASaveItsCachedCopyMissedLeftIt,TestAPatchWritesAFieldItSendsThatItsCachedCopyAlreadyHeld,TestAnUpdateWritesAFieldItSendsThatItsCachedCopyAlreadyHeld,TestASyncKeepsAModelSavedSinceItReadTheConfigThatItsDirectoryDoesNotDeclare,TestASyncWritesWhatItsDirectoryDeclaresOverASaveItsCachedCopyMissedupdated_atonAgentConfigPatch, compared for equalityconflict, also when a replica's clock was behind. Without the field, nothing changes for the callerTestAPatchMadeFromACopyOlderThanTheConfigIsRefused,TestAPatchSendingTheUpdatedAtItWasLastGivenIsWritten,TestASaveFromACopyOlderThanTheConfigIsRefusedWhenAskedTo,TestASaveIsRefusedOverASaveWhoseClockWasBehind"", then the hash after skills and simulations, only over its own write (sync.go)TestASyncWhoseSkillsFailedOnceWritesThemWhenSentAgain,TestASyncLeavesItsHashOffAConfigSavedWhileItWroteItsSkillsusers.claim_finished_at(migration20270201000700),Store.FinishGuestClaim, same-account claim runs every step until it is set (guests.go,store/sessions.go)TestAClaimThatStoppedAfterMovingTheRowsJoinsTheChannelsWhenSentAgain,TestAFinishedClaimSentAgainLeavesTheChannelsAsTheyAre,TestAGuestClaimIsFinishedOnlyForTheAccountThatClaimedItAPI behaviour
PATCH /v1/agents/configs/{id}takes an optionalupdated_at. It is enforced only when sent, so existing clients keep working. No client sends it today: JSupdateConfig(sdks/js/src/handle.ts:59) and GoUpdateConfig(sdks/go/client/client.go:242) send a patch without it.AgentConfigPatchisadditionalProperties: 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 storedupdated_atat microseconds, so a GET's microseconds and a PATCH response's nanoseconds both pass.conflict("send it again"). Each lost try means another save landed, so 5 saves of one config at once all land.sessions_moved: 0at once, as on main. One that stopped part-way does the remaining work again;sessions_movedcounts what that call moved.20270201000700_guest_claim_finished.sql(global) adds the nullableusers.claim_finished_at. Guests claimed before it have none, so the same claim sent again runs its steps once more and is then marked.api/openapi.yaml, the Python client, the JS types and the Go SDK. The Swift--checkis unchanged, because both operations are server-side only. The SDK note.claude/skills/sdk/notes/2026-11-23-ai-3516.mdlists what .NET, Ruby, Rust and PHP still need.Judgment calls (please check)
floorControlComplaintasks the chorus-asr server,regionComplaintasks each router'sInRegionandknowledge.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.fillKnowledgeskips a document whose text is unchanged, and the page subscriptions and the forget are idempotent, so a lost race costs reads, not re-indexing.Savethat is refused as stale if anyone saved the config in between.claimed_byis still written first, in the same transaction as the moves (ClaimGuest's doc), or another account could claim the guest in between.claim_finished_atis 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).Updatelocked the row last. The comments onlockBoundConnectionsandlockChannelOwnersay why no cycle remains: neither a connection delete norInsertlocks a stored config row.Update's query budget goes from 3 to 4: begin, the locked read, the update, commit.Saveis the same 4.TestAPatchFromACopyReadBeforeASyncStillHasTheNextSyncWriteAgainfrom the first version of this PR is gone: it guarded the column merge, which no longer exists.Validation
Run from
acceleration/at 294648e (onmainat ef6b972), against an isolated test database and Redis:go build ./...,go vet(with and without-tags integration) oninternal/storeandinternal/api,gofmt -l: cleango test -count=1 ./internal/store/ ./internal/api/: passgo test -tags integration -p 1 ./internal/api/(the whole package): passgo test -tags integration -p 1 ./internal/store/(the whole package, on databases recreated after the rebase): everything passes butTestEveryTableWithAUserIDIsForgottenOrKeptForAReasonin both suites. It fails the same way onmainat ef6b972: it findscalls.agent_user_id, which nothing here touches.TestEveryHotTableIsReadByIndex/Requests.Inserttimed out once reading the shared test Postgres and passed on rerun.go run ./cmd/openapi,go run ./cmd/schemaandgo generate ./...insdks/go: nothing left to change..agents/skills/pr-review/scripts/generated.sh . origin/main: in step. The review fixes do not changeopenapi.yaml. The Python generator cannot run offline here; run with the cachedopenapi-python-client0.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:
TestASyncWritesWhatItsDirectoryDeclaresOverASaveItsCachedCopyMissedDashboard wording.TestAPatchIsCheckedAgainstTheConfigAsASaveItsCachedCopyMissedLeftItTestAPatchWritesAFieldItSendsThatItsCachedCopyAlreadyHeld,TestAnUpdateWritesAFieldItSendsThatItsCachedCopyAlreadyHeldBe loud.TestAFinishedClaimSentAgainLeavesTheChannelsAsTheyAreTestASyncLeavesItsHashOffAConfigSavedWhileItWroteItsSkillsShould be empty, but was v1. The first version had the condition, so it passes thereTestASaveMadeFromACopyAnotherSaveReplacedWritesNothingsaveTestASaveIsRefusedOverASaveWhoseClockWasBehindAfterin place ofEqualTestAGuestClaimIsFinishedOnlyForTheAccountThatClaimedItclaimed_by = ?dropped fromFinishGuestClaimTestASyncKeepsAModelSaved…)Checked in the first version of this PR, against
main:TestPatchesAtOnceToDifferentFieldsAllSurvive(round 0:instructionslost to a concurrent patch),TestASyncWhoseSkillsFailedOnceWritesThemWhenSentAgain(answeredunchanged, no skill),TestASyncKeepsAModelSavedSinceItReadTheConfigThatItsDirectoryDoesNotDeclare(llmwent back),TestAClaimThatStoppedAfterMovingTheRowsJoinsTheChannelsWhenSentAgain(not a member),TestAPatchMadeFromACopyOlderThanTheConfigIsRefusedandTestAPatchSendingTheUpdatedAtItWasLastGivenIsWritten(400:updated_atunknown).🤖 Generated with Claude Code