Repository navigation
feat(engine): intent claim heartbeat, TTL and fencing token (S3c) - #176
Merged
Merged
Conversation
An intent claim was atomic but had no heartbeat, no expiry and no owner token: startup reset every running intent to open unconditionally, so a second instance on the same database stole live claims, and the worker that lost its intent could still write the result. - schema: last_heartbeat_at and unclaim_token on exploration_nodes (idempotent ADD COLUMN IF NOT EXISTS, nullable, no CHECK, no backfill). - db: every claim (open->running and the paused->running message path) gets a fresh crypto/rand token and starts its lease in the same UPDATE. HeartbeatIntentClaim renews it for that token only. - TTL: db.IntentClaimTTL = 90s, heartbeat every 15s (db.IntentClaimHeartbeatInterval), both on the database clock. - takeover: ResetRunningIntents now reopens only claims whose heartbeat is older than the TTL, or NULL (rows claimed before the columns existed). The engine runs it per task every 15s as well as at startup. - fencing: a heartbeat or result write whose token is not the current one returns db.ErrIntentClaimLost and writes nothing. All intent state writes in runIntent go through the fenced SettleIntentClaim / SettleIntentClaimBlocked; a rejected heartbeat cancels the stale run with the new work_claim_lost cause. Behaviour change: after a restart, intents that were in flight are resumed once their claim expires (at most 105s) instead of immediately. Not in this change: fencing of the facts, findings and activity a worker writes during its run; they are not guarded by the token.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
An intent claim now has a lease and an owner token (S3c).
exploration_nodes,last_heartbeat_at TIMESTAMPTZandunclaim_token TEXT, added withALTER TABLE ... ADD COLUMN IF NOT EXISTSindb/schema.sqlnext to the existingexploration_nodescolumn migrations. No CHECK constraint, no backfill.unclaim_token(16 bytes fromcrypto/rand, hex) and stampslast_heartbeat_at = now()in the sameUPDATEthat moves the intent torunning. This covers both entries intorunning: the worker pool (open -> running,ClaimIntentToken) and the human-message path (paused -> running,ClaimPausedIntentToken).ClaimIntentkeeps its signature and callsClaimIntentToken.runIntentruns a heartbeat goroutine that callsHeartbeatIntentClaim(id, token)every 15 s. It updates the row only wherestate='running' AND unclaim_token=<its token>. It stops when the worker run has returned, just before the result is written.ResetRunningIntentsreopens a running intent only whenlast_heartbeat_atis older than the TTL, or NULL. It is still called at startup, and the engine now also calls it per started task every 15 s (claimSweepLoop), because a claim that is still live at startup has to be picked up later, once it expires.runIntentgoes throughSettleIntentClaim/SettleIntentClaimBlocked, which requirestate='running' AND unclaim_token=<token>and clear the token on success.Why
ClaimIntentwas already atomic, but the claim had no heartbeat, no expiry and no owner token:runningintent of every task toopen, unconditionally. A second instance started against the same database took over the first instance's live intents.CompareAndSetIntentState(running -> done)succeeded, because the row wasrunningagain under the new claimer. The quota path (SetIntentBlockedReason) had no state check at all.TTL
db.IntentClaimTTLdb.IntentClaimHeartbeatIntervalRationale:
running: at most TTL plus one sweep interval, 105 s. A worker run lasts minutes (the default per-run limit is 1200 s) and the planner heartbeat floor is 600 s, so 105 s is small next to both.now()in the same statement), never on an instance's clock, so clock skew between instances does not matter.Fencing behaviour
db.ErrIntentClaimLostand writes nothing. The heartbeat goroutine then cancels that run with the new causeagent.AbortWorkClaimLost(work_claim_lost), andrunIntentreturns without writing any state.db.ErrIntentClaimLostand writes nothing. This also holds between the takeover and the re-claim (token cleared, stateopen), and for a stale worker that finishes before its next heartbeat.runIntentlogs the rejection; on the normal-completion path it also skips the "finished" log andNotifyDone.running(changed by an unfenced control path), the write returnsdb.ErrIntentStateConflict, as before.UPDATEs on the row, so exactly one wins: either the claim is renewed and stays, or it is taken over and the heartbeat is rejected.server/engine.go,runIntent): the claim rollback when the task is paused or being deleted,pausedfor user pause and for user cancel,openon task pause,exhaustedon timeout settlement,stoppedon task completion and on planner kill, the finaldone/blocked/exhausted, and the LLM-quotablockedwrite. That last one was an unconditionalSetIntentBlockedReasonwhose error was discarded; it now also requiresstate='running'and its error is logged.Legacy rows
A
runningrow withlast_heartbeat_at IS NULLwas claimed before these columns existed. It is treated as expired and may be taken over immediately. This is the previous startup behaviour for exactly those rows, so an upgrade resumes in-flight intents as it did before. The migration writes nothing to existing rows.Consequence: this is not safe for mixed versions on one database. An old binary never heartbeats and its writes are not fenced, so a new instance would take its live claims. All instances on a database have to run this version.
Behaviour changes to be aware of
runninguntil then. This follows from "a live claim is never taken over": at startup a claim renewed a few seconds ago cannot be told apart from another instance's live claim.work_claim_lost) and the intent is claimed again and resumes from its transcript.updated_aton a running intent row now moves every 15 s (the table'sBEFORE UPDATEtrigger). Nothing in the Go code readsexploration_nodes.updated_at.Tests
New, Postgres-backed, skipped without
ARTEX_PG_DSNlike the rest ofdb/:db/intent_claim_test.go(each test opens the database twice, as two instances):TestIntentClaimLiveClaimIsNotReclaimed: neither instance reopens or re-claims a live claim, including one 10 s short of the TTL.TestIntentClaimExpiredClaimIsReclaimed: past the TTL it is reopened, the token is cleared, and the re-claim gets a different token.TestIntentClaimLegacyRunningRowIsReclaimed: a running row with NULL lease columns is reopened.TestIntentClaimHeartbeatExtendsLease: a heartbeat on an expired, not yet taken over claim keeps it; without a further heartbeat it expires.TestIntentClaimStaleWorkerIsFencedAfterReclaim: after the takeover, and again after the re-claim, the old worker's heartbeat, result write and blocked write all returnErrIntentClaimLostand leave the row unchanged; the new claimer's heartbeat and result write succeed.TestSettleIntentClaimBlockedAndStateConflict,TestClaimPausedIntentTokenStartsLease.TestIntentClaimTakeoverRacesHeartbeatAtomically: 40 rounds of a heartbeat racing a takeover from the other instance, exactly one winner per round.TestIntentClaimColumnsMigrateIdempotently: drops the two columns, inserts a running intent, runs the embeddedschema.sqltwice in a rolled-back transaction, checks column types, nullability, no CHECK constraint, and that the legacy row keeps NULLs.server/claim_heartbeat_test.go:TestClaimHeartbeatRenewsThenCancelsOnTakeoverruns the heartbeat goroutine at 20 ms, checks that it renews an expired-looking claim, then that a takeover cancels the run withAbortWorkClaimLost.Mutation check (not committed): making the takeover ignore the heartbeat age, dropping the token check from the result write, or dropping it from the heartbeat each fails at least one of these tests.
Results
Go 1.26.10 linux/amd64,
postgres:16-alpine(PostgreSQL 16.15) in a throwaway container, a newly created database for every run.go build ./...: exit 0go vet ./...: exit 0go test ./db/ -count=1:ok github.com/Autumn-27/artex/db 30.629s, exit 0. With-v: 185 top-level tests passed, 0 failed, 0 skipped.go test ./... -count=1: exit 0go test -race -p 1 -count=1 ./db ./agent: bothok.go test -race -count=1 ./server -run TestClaimHeartbeat:ok.gofmt -don the six changed Go files (CR-stripped): no diff.origin/mainschema (loaded withpsql, plus onerunningintent): the newschema.sqlapplied twice withpsqlwithout error; both columns present and nullable; the legacy row staysrunningwith NULL in both.db.Openand the claim tests then pass against that database.Not verified
runIntent, the heartbeat start/stop placement, the claim-lost branch and the fenced settle calls are covered by build, vet and the tests above, not by a run ofrunIntentitself. The repository has no harness that drivesrunIntent.claimSweepLoop(the 15 s periodic sweep) and therunDetachedIntentwiring have no test of their own. The store calls they make are tested../serverpackage was not run under-race(CI does not run it under-raceeither).go test -p 1 ./...form was not run; the runs above use the default package parallelism.Not in this change