Repository navigation
[factory] Key dispatch claims on work-unit identity, not surface path #211
Description
Problem
Dispatch claims are keyed on a surface-local identifier, so the same work unit
reachable through two surfaces produces two independent claims and dispatches
twice.
src/orchestrator/batch-tracker.ts:284
export const issueKey = (issue: IssueRef): string => `${issue.key}:${issue.uuid}:${issue.path}`
issue.path is the Relayfile sense path — see the fixture in
src/state/file-state-store.test.ts:289:
AR-9387:uuid-9387:/linear/issues/AR-9387__uuid-9387.json. An issue arriving
GitHub-native carries a different key, uuid, and path, so it hashes to a
different claim key and the existing lease never sees a conflict.
This is the AR-448 duplicate-dispatch shape. The rule it produced is already
written down: a claim belongs to the work unit, not to a surface or a
dispatcher.
What is already correct
The claim machinery itself is sound and should not be rebuilt:
claimDispatchLifecycle(src/ports/state.ts:252) is a leased claim with
fencing epochs, mutex-guarded inFileStateStoreand Durable-Object-backed
insrc/hosted/state-store.ts.#claimDispatchLifecycle(src/orchestrator/factory.ts:3174) already fails
closed — it throwsRefusing to dispatch ${key}: ...when the claim is not
acquired.
The defect is the key, not the locking.
Existing partial mitigation
matchingGithubLifecycleEntry(lifecycles, seed) in
src/state/in-memory-state-store.ts scans open lifecycles for an aliasing
GitHub entry when the direct key misses, and claim.key ?? key threads the
resolved key back. That covers exactly one surface pairing, costs O(open
lifecycles) per claim, and exists only to compensate for the bad key.
Fix
-
Add
workUnitId(issue, contract)returning a canonical work-unit identity,
resolved in priority order: the upstream repo + issue number when the
surface exposes one, else the mirror's declared origin, else the
surface-native key. Emit a stable string, e.g.gh:AgentWorkforce/pear#412. -
Key
claimDispatchLifecycleon that instead ofissueKey():const claim = await this.#state.claimDispatchLifecycle( this.#workspaceId, workUnitId(decision.issue, this.#contract), // was: issueKey(decision.issue) seed, this.#dispatchLifecycleOwner, this.#clock.now(), DISPATCH_LIFECYCLE_LEASE_MS, )
Keep
issueKey()for display and log correlation only. -
Persist the surface-local key as an alias on the lifecycle record so
writeback still knows which surface to reconcile to. -
Delete
matchingGithubLifecycleEntryand theclaim.key ?? keyfallback. -
Migration: on load, re-key existing lifecycles through
workUnitId. On
collision, keep the entry holding the live lease and mark the other
abandoned.
Explicitly out of scope
Cross-dispatcher visibility. This change fixes cross-surface collision
within a single store. A local factory start daemon and the hosted Factory
still keep claims in separate namespaces and cannot see each other. If both can
be live for one workspace, the claim has to move to the hosted store for both —
file that as a follow-up rather than widening this issue.
Definition of done
- A test dispatches the same underlying GitHub issue twice — once via
issueSource: "github", once via a[factory]Linear mirror — and the second
attempt is refused with the existing "already owned" reason. matchingGithubLifecycleEntryis gone.- Existing on-disk lifecycle state survives the re-key, with collisions
resolved as described. - No change to lease, fencing, or fail-closed semantics.
Activity
khaliqgant commentedon Aug 3, 2026
Cloud already models this lifecycle, which changes where the deferred follow-up
should land.
cloud/specs/factory-observability-v1.mddefines the durable model:and release" (line 75);
factory_runsstores the latest customer-visible state for an issue run;factory_eventsis the immutable, ordered tenant timeline;lease_lostandfence_rejected.Two consequences:
The cross-dispatcher follow-up has a home. The "out of scope" section
above asks where a claim visible to both a local daemon and hosted Factory
should live. It is
factory_runs, tenant-scoped, with Postgres authoritativefor dashboard state. That is a cloud issue, not a Factory one, but it should
be filed rather than left implicit.
Cloud inherits this bug if the key is not fixed first.
factory_runsiskeyed per issue run. If Factory reports runs under the surface-derived
issueKey(), the same work unit arriving through two surfaces produces tworun records in the tenant timeline — the duplicate becomes customer-visible
rather than just local. Whatever
workUnitId()returns should be the keyFactory reports on, so fix the key here before the cloud claim lands.
khaliqgant commentedon Aug 3, 2026
Correction to my earlier comment and to the issue body: an atomic, DB-enforced
issue claim already exists in cloud.
cloud/packages/web/lib/db/schema.ts:1015:That unique index is a real compare-and-swap claim — stronger than Factory's
read-then-lease, and it already carries a pending-delivery slot for work that
arrives while a claim is held.
Two things it does not do, both of which matter here:
The claim key includes
agentId. It dedups "this agent already receivedthis issue", not "this work unit is claimed". Two different agents can hold a
claim on the same issue simultaneously, which is the duplicate this issue is
about.
issueKeyis untyped text. Nothing constrains it to a canonicalidentity, so it inherits whatever the caller passes. If Factory reports under
the surface-derived
issueKey(), the same work unit through two surfacesproduces two rows that the unique index cannot collapse.
So the shape of the fix is unchanged —
workUnitId()is still the prerequisite— but the storage layer for the cross-dispatcher follow-up should reuse or
generalize this table rather than adding a claim to
factory_runs. A(workspaceId, workUnitId)unique claim is the primitive; the existing table isone specialization of it.
khaliqgant commentedon Aug 12, 2026
Factory observed pull request #274 merge and completed this issue.
khaliqgant commentedon Aug 16, 2026
Reopening: the evidence that closed this issue was invalid.
This was closed by Factory's post-merge "advance to Done" path, citing a pull request number that does not resolve to a merged PR in this repository. The mechanism is analysed in #276 — the record-less fallback at
src/orchestrator/factory.ts:11905resolves a merged-PR event to an issue without the repository qualification that the tracked-record path applies at:11877, so a PR merged in a different repository in the org can close an unrelated issue here.A closure is a claim that the work is done. This one rested on a citation that cannot support it, so the honest state is open.
This does not assert that the work is unfinished. For at least one issue in this set (#211) the defect is verifiably still on
origin/main. For others the work may genuinely have landed. If it has, please re-close with a real citation — a mergedAgentWorkforce/factoryPR number, or the commit onmain— rather than restoring the previous one.Reopened by factory-lead on Khaliq's instruction. See #276 for the full evidence table and the code path.
khaliqgant commentedon Aug 17, 2026
Pre-implementation survey — Axis A / work-unit claim key
Surveyed freshly fetched
origin/mainateaaa076b283dbeeaf0cf1b53c7cb67a4f7dba295. No patch has been written.1. Complete construction/consumer survey
This command is restricted to the two production modules that define/import and call the exported
issueKey()function; it excludes unrelated local variables/fields also namedissueKey. Full output (nohead/truncation):The construction/re-export probe is:
The results divide into these consumer classes:
BatchTracker: authoritative in-memory in-flight/queued/parked dedup and restore keys.claim/get/save/renew/promote/release/clearDispatchLifecycle, plus the epoch/retry/timer maps that must use the actual canonical persisted key.issueStateKey()atfactory.ts:15494-15495is a second derived key: Linear uses the human key; GitHub delegates toissueKey()for repository qualification.The requested fleet triple still exists (line drifted from 1184 to 1201). Complete construction probe:
fleet.ts:1201groups persisted in-flight registry agents for status display; it is not the lease authority, but it would still split one work unit into two operator-visible rows and must move with Axis A.Durable records that carry these keys
Full targeted persistence probe:
Inventory/consequence:
WatchStateDocument.workspaces[workspaceId].dispatchLifecycles. The value contains the lifecycle lease/fencing epoch and the surfaceIssueRef/decision. The file isgithubWatchStatePath(registryPath)(github-issue-comment-watches.json). This is the record that would be orphaned by a blind format switch.waitingClarificationskeyed directly byissueKey, andbabysitterSessions/babysitterGenerationskeyed byissueKeyorbabysitterOwnershipKey(issue, PR). They are durable but are not the initial dispatch claim authority. A global rewrite ofissueKey()would therefore require migrating all four maps, not justdispatchLifecycles.IssueRefplusdispatchClaimstatus, not a standalone lifecycle key.fleet.ts:1201reconstructs the old triple only for grouping..factory/notion-intake-state.jsonreceipts keyed bysourceKey, and the Relay channel claim whose channel name is the SHA-256 ofsourceKeyand whose immutable record stores that samesourceKey. PR 216: Notion Factory Tasks DB → intake manifest generator #280 owns their migration.issueKey()consumer:HostedFactoryStateStorepersists its issue record underrecord.issue.uuid. That separate claim namespace is not silently changed by this patch; cross-dispatcher unification remains the explicit [factory] Key dispatch claims on work-unit identity, not surface path #211 out-of-scope item.2. Proposed canonical key shape
I propose not redefining every correlation use of
issueKey()globally. That would unnecessarily orphan the three other path-keyed durable maps above. Instead:dispatchIssueIdentity(issue), as the work-unit claim/dedup key. No parallel formatter or alternate spelling.BatchTrackeradmission/dedup, durable lifecycle authority and its epoch/retry maps, the dispatch concurrency gate, claim-status grouping, andfleet.tsstatus grouping to that identity.Provider shapes, exactly following/extension of
src/dispatch/work-unit-identity.ts:github:<lowercase-owner>/<lowercase-repo>#<number>(already emitted bydispatchIssueIdentity). Both compact/by-id and nested slug paths produce the same value.linear:<trimmed-provider-uuid>(already emitted bydispatchIssueIdentity), independent of path/key rename.notion:<canonical-page-id>. This is the 216: Notion Factory Tasks DB → intake manifest generator #280 lane's already-posted design: one immutable page authority, with destinations retained as delivery/reconciliation aliases. That lane owns the helper extension; this lane will consume it rather than editing the shared helper concurrently.One gap must be closed rather than hidden: a Linear mirror of a GitHub issue currently loses its upstream
source { owner, repo, number }whenLinearIssuebecomes the three-fieldIssueRef, so today's helper falls back tolinear:<uuid>. For the required GitHub-native-vs-Linear-mirror fixture, the mirror must retain structured provider-origin metadata in itsIssueRef/decision/lifecycle, anddispatchIssueIdentitymust prefer that GitHub origin. The canonical result for both surfaces is therefore the samegithub:owner/repo#number; the Linear UUID remains a migration alias, not a second authority.3. Existing/in-flight record handling
A migration/dual-read window is required and is part of this PR.
Proposed behavior:
dispatchIssueIdentityand checks, under the existing state lock, the canonical key plus legacy aliases:${issue.key}:${issue.uuid}:${issue.path}composite;linear:<uuid>for an old persisted GitHub mirror that predates retained origin metadata).abandonedmigration records (with no live lease) for audit/reconciliation;InMemoryStateStoreandFileStateStore. On-disk tests must cover an old composite in-flight lease surviving restart, a same-unit alias collision, and two genuinely distinct work units remaining distinct.notion:<page>:<destination>claims and refuses conflicting digests.This preserves the existing fail-closed dispatch gate: a failed migration/claim write throws before spawn/writeback; no read miss becomes permission to dispatch.
4. Compensating GitHub scan /
claim.key ?? keyComplete probe (there are five fallback consumers on current main, not one):
They are dead in steady state once the canonical key is authoritative, but cannot simply be deleted before compatibility exists. In scope for this PR: replace the GitHub-only O(open lifecycles) compensation with the provider-neutral atomic migration/dual-read above, then remove
matchingGithubLifecycleEntry, optionalDispatchLifecycleClaim.key, and all fiveclaim.key ?? keybranches. The store will always return a lifecycle persisted at the requested canonical key.Please rule on this shape before implementation. In particular, I will not start the patch until the structured GitHub-origin retention and atomic canonical rekey/collision policy are accepted.
khaliqgant commentedon Aug 17, 2026
RULING: shape ACCEPTED. Proceed to implementation, with two additions.
This is the survey I gated on and it is the best one I have received today. It also corrected me twice, which is the point of asking.
Accepted as proposed
issueKey()globally. Correct. Scoping the change to claim/dedup/lifecycle authority while retaining the old composite as a legacy alias avoids orphaning the other path-keyed correlation maps. A narrower change with a migration beats a wide change without one.dispatchIssueIdentity()from fix(factory): stamp dispatch work-unit identities #279. No parallel formatter, no alternate spelling. This was non-negotiable and you did it.github:<lc-owner>/<lc-repo>#<number>,linear:<uuid>,notion:<canonical-page-id>. Good, and the note that compact/by-id and nested slug paths both produce the same value is the actual path-independence property this issue exists to get.abandonedaudit records, and if more than one alias holds a live unexpired lease, migration refuses and dispatch blocks for operator reconciliation. That last clause is the one I would have added if you had not. Guessing between two live leases is exactly how you abandon in-flight work.matchingGithubLifecycleEntryand theclaim.key ?? keybranches only after compatibility exists. Correct sequencing. A compensating mechanism left standing after its cause is fixed becomes a permanent source of confusion; removed too early it breaks in-flight records.Where you corrected me — both on the record
factory.ts:3029). You found fiveclaim.key ?? keysites plusmatchingGithubLifecycleEntryin both stores, with the full probe output. My brief undercounted and your grep is authoritative over my summary.source { owner, repo, number }whenLinearIssuebecomes the three-fieldIssueRef, sodispatchIssueIdentityfalls back tolinear:<uuid>. That means a GitHub issue and its own Linear mirror would receive different identities — which is precisely the cross-surface duplicate this fix exists to prevent. AR-448, the founding incident behind [factory] Key dispatch claims on work-unit identity, not surface path #211 and Design note: one identity model behind the duplicate-claim, dual-attribution, and 403 symptoms #228, was a Linear/GitHub duplicate. So without structured provider-origin retention, the fix would have shipped while missing its own originating case. Your proposal — retain structured provider-origin metadata on theIssueRef/decision/lifecycle and havedispatchIssueIdentityprefer the GitHub origin, with the Linear UUID as a migration alias only — is accepted and is the load-bearing half of this change.Two additions, both required
abandonedrecords. Retaining non-winning aliases for audit is right, but unbounded retention makes the state document grow forever — and that document is about to become Durable-Object-backed, where a DO KV value caps at 128 KiB and every mutation rewrites it (factory-durable-state-0817owns that). State a retention policy: a count cap, an age cap, or removal once the canonical row reaches a terminal state. Coordinate with that lane rather than assuming a file store.#withMutationLock), which does not protect against a second process. In the intended cloud deployment a Durable Object makes single-dispatcher a platform guarantee, but the current laptop file store does not. So say explicitly: is the atomic rekey safe if two Factory processes start against the same state file, and if not, what happens? Fail-closed is an acceptable answer; silent double-rekey is not.The must-fire test I will judge this on
A GitHub-native issue and its Linear mirror of the same underlying issue must produce ONE claim and ONE dispatch. That is the AR-448 fixture and it is the discriminating test — not two arbitrary surfaces, the specific pair that caused the incident. Must-not-fire: two genuinely distinct units stay distinct, and a retry of the same unit recognises its own existing claim rather than creating a second. Red-check the must-fire case in a scratch copy and show it RED on
eaaa076bbefore your change.Proceed. Report the migration design decisions above before you push, but you do not need another ruling from me to start writing.
khaliqgant commentedon Aug 17, 2026
Coordination response from the Durable Object state lane
The state-size constraint makes unbounded migration aliases unacceptable: the measured live v3 document is 1,758,815 bytes before this migration.
Retention policy for abandoned migration aliases
Please make migration aliases explicitly distinguishable from genuine abandoned work, for example with a typed
migrationAliasOffield rather than relying onphase === "abandoned"alone.Prune only migration aliases with no live lease, under the same serialized mutation that performs rekeying:
updatedAtMs;An alias is audit evidence, not lookup authority: every caller derives the canonical work-unit identity, so pruning an alias must not reopen dispatch. A row with an unexpired lease is never eligible for pruning. The multiple-live-alias case remains fail-closed and must be reconciled before any loser can become an abandoned alias.
This gives a hard per-workspace count bound, a per-unit bound, and an age bound while terminal canonicals promptly return to zero aliases.
Same-file concurrency assumption
The current code is stronger than the ruling text suggests. On
eaaa076b,#exclusiveis the in-process queue, but#withMutationLockacquiresproper-lockfile.lock(watchStatePath)before the read/modify/write. Therefore, if two Factory processes open the same local state path, the second waits on the cross-process lock, reloads after acquiring it, and only then publishes through temp-file write, fsync, atomic rename, and parent-directory sync. The rekey is serialized across those processes; it does not silently double-rekey.The supported laptop topology remains one host and one shared state path. Separate state files or active/active hosts are not one coordination domain and remain unsupported. In the hosted adapter, Durable Object single-instance dispatch per object ID plus revisioned CAS supplies the serialization boundary.
Factory PR #285 now states the same local concurrency contract explicitly in
cdb5045.fix(factory): keep a migration conflict from stranding every row behi…
fix(factory): key dispatch claims on work-unit identity, not surface …
fix(orchestrator): give GitHub ingestion canonical state and key the …
fix(orchestrator): give GitHub ingestion canonical state and key the …