Skip to content

feat(engine): intent claim heartbeat, TTL and fencing token (S3c) - #176

Merged
BaaRai merged 1 commit into
mainfrom
feat/claim-heartbeat-fencing
Nov 10, 2026
Merged

BaaRai merged 1 commit into
mainfrom
feat/claim-heartbeat-fencing

Conversation

@BaaRai

@BaaRai BaaRai commented Nov 10, 2026

Copy link
Copy Markdown
Owner

What

An intent claim now has a lease and an owner token (S3c).

  • Schema: two nullable columns on exploration_nodes, last_heartbeat_at TIMESTAMPTZ and unclaim_token TEXT, added with ALTER TABLE ... ADD COLUMN IF NOT EXISTS in db/schema.sql next to the existing exploration_nodes column migrations. No CHECK constraint, no backfill.
  • Token: every claim writes a fresh unclaim_token (16 bytes from crypto/rand, hex) and stamps last_heartbeat_at = now() in the same UPDATE that moves the intent to running. This covers both entries into running: the worker pool (open -> running, ClaimIntentToken) and the human-message path (paused -> running, ClaimPausedIntentToken). ClaimIntent keeps its signature and calls ClaimIntentToken.
  • Heartbeat: while a worker is busy with an intent, runIntent runs a heartbeat goroutine that calls HeartbeatIntentClaim(id, token) every 15 s. It updates the row only where state='running' AND unclaim_token=<its token>. It stops when the worker run has returned, just before the result is written.
  • Takeover: ResetRunningIntents reopens a running intent only when last_heartbeat_at is 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.
  • Fencing: every intent state write in runIntent goes through SettleIntentClaim / SettleIntentClaimBlocked, which require state='running' AND unclaim_token=<token> and clear the token on success.

Why

ClaimIntent was already atomic, but the claim had no heartbeat, no expiry and no owner token:

  • Startup reset every running intent of every task to open, unconditionally. A second instance started against the same database took over the first instance's live intents.
  • The worker that lost its intent this way kept running, and its final CompareAndSetIntentState(running -> done) succeeded, because the row was running again under the new claimer. The quota path (SetIntentBlockedReason) had no state check at all.

TTL

constant value meaning
db.IntentClaimTTL 90 s a running intent with no heartbeat for longer than this may be taken over
db.IntentClaimHeartbeatInterval 15 s how often a busy worker renews its claim, and how often the engine sweeps for expired claims

Rationale:

  • The heartbeat is the only liveness signal, and it runs in its own goroutine, so it measures "the process is alive and can reach Postgres", not worker progress. A long LLM call or tool run does not delay it.
  • Too short costs more than too long. If a live worker loses its claim, the intent is run a second time: duplicate LLM spend and duplicate traffic at the target. 90 s is six intervals, so a live worker is only exposed after five consecutive missed heartbeats, about 75 s without database connectivity. That covers a Postgres container restart or a short network cut.
  • Too long delays recovery. The TTL bounds how long a dead worker's intent stays 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.
  • Expiry is compared on the database clock (now() in the same statement), never on an instance's clock, so clock skew between instances does not matter.

Fencing behaviour

  • A heartbeat whose token is not the running intent's current token returns db.ErrIntentClaimLost and writes nothing. The heartbeat goroutine then cancels that run with the new cause agent.AbortWorkClaimLost (work_claim_lost), and runIntent returns without writing any state.
  • A result write whose token is not current returns db.ErrIntentClaimLost and writes nothing. This also holds between the takeover and the re-claim (token cleared, state open), and for a stale worker that finishes before its next heartbeat. runIntent logs the rejection; on the normal-completion path it also skips the "finished" log and NotifyDone.
  • If the token is still current but the intent is no longer running (changed by an unfenced control path), the write returns db.ErrIntentStateConflict, as before.
  • The takeover and a concurrent heartbeat of the same claim are both single 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.
  • Guarded write paths (all in server/engine.go, runIntent): the claim rollback when the task is paused or being deleted, paused for user pause and for user cancel, open on task pause, exhausted on timeout settlement, stopped on task completion and on planner kill, the final done / blocked / exhausted, and the LLM-quota blocked write. That last one was an unconditional SetIntentBlockedReason whose error was discarded; it now also requires state='running' and its error is logged.

Legacy rows

A running row with last_heartbeat_at IS NULL was 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

  • Restart: intents that were in flight when the process stopped are no longer reopened immediately at startup. They are reopened when their claim expires, at most 105 s after the last heartbeat, and show as running until 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.
  • Database outage longer than the TTL: when Postgres comes back, the sweep may reopen an intent whose worker is still alive in the same process, if it runs before that worker's next heartbeat. The worker is then cancelled (work_claim_lost) and the intent is claimed again and resumes from its transcript.
  • updated_at on a running intent row now moves every 15 s (the table's BEFORE UPDATE trigger). Nothing in the Go code reads exploration_nodes.updated_at.
  • Tasks whose engine loops are not running (queued or terminal at startup) only get the startup pass; the periodic sweep starts with their loops.

Tests

New, Postgres-backed, skipped without ARTEX_PG_DSN like the rest of db/:

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 return ErrIntentClaimLost and 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 embedded schema.sql twice in a rolled-back transaction, checks column types, nullability, no CHECK constraint, and that the legacy row keeps NULLs.

server/claim_heartbeat_test.go: TestClaimHeartbeatRenewsThenCancelsOnTakeover runs the heartbeat goroutine at 20 ms, checks that it renews an expired-looking claim, then that a takeover cancels the run with AbortWorkClaimLost.

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 0
  • go vet ./...: exit 0
  • go 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 0
ok  	github.com/Autumn-27/artex/agent	13.116s
ok  	github.com/Autumn-27/artex/cmd/artex	0.044s
ok  	github.com/Autumn-27/artex/config	0.009s
ok  	github.com/Autumn-27/artex/db	60.672s
?   	github.com/Autumn-27/artex/enrich	[no test files]
ok  	github.com/Autumn-27/artex/evidence	11.912s
ok  	github.com/Autumn-27/artex/guard	0.006s
ok  	github.com/Autumn-27/artex/intercept	0.009s
ok  	github.com/Autumn-27/artex/llmpool	0.007s
ok  	github.com/Autumn-27/artex/llmrec	0.006s
ok  	github.com/Autumn-27/artex/mcphttp	7.024s
ok  	github.com/Autumn-27/artex/notify	0.104s
?   	github.com/Autumn-27/artex/report	[no test files]
ok  	github.com/Autumn-27/artex/server	73.787s
ok  	github.com/Autumn-27/artex/sidequestion	0.038s
ok  	github.com/Autumn-27/artex/traffic	15.226s
  • go test -race -p 1 -count=1 ./db ./agent: both ok. go test -race -count=1 ./server -run TestClaimHeartbeat: ok.
  • gofmt -d on the six changed Go files (CR-stripped): no diff.
  • Database created with the origin/main schema (loaded with psql, plus one running intent): the new schema.sql applied twice with psql without error; both columns present and nullable; the legacy row stays running with NULL in both. db.Open and the claim tests then pass against that database.

Not verified

  • No end-to-end run with a real worker and LLM. In 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 of runIntent itself. The repository has no harness that drives runIntent.
  • claimSweepLoop (the 15 s periodic sweep) and the runDetachedIntent wiring have no test of their own. The store calls they make are tested.
  • Two real server processes against one database were not started. The two-instance tests use two connection pools in one test process.
  • The full ./server package was not run under -race (CI does not run it under -race either).
  • The CI go test -p 1 ./... form was not run; the runs above use the default package parallelism.

Not in this change

  • The facts, findings and activity a worker writes during its run are not fenced by the token. A worker that lost its claim can still append them until its next heartbeat is rejected (at most 15 s after the re-claim) and its run winds down.
  • No UI change, no CHANGELOG entry.

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.
@BaaRai
BaaRai merged commit 7ccae15 into main Nov 10, 2026
4 checks passed
@BaaRai BaaRai mentioned this pull request Nov 11, 2026
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.

1 participant