Repository navigation
feat(agent-status): add the canonical store and child-work contract - #20717
Conversation
|
Electron smoke screenshot at d94b0d1: an isolated, hidden/background Orca dev instance rendering the Workspace board with a disposable QA Sandbox folder workspace. The canonical contracts in this PR are not imported or wired to the UI; this image verifies only existing app rendering, not canonical-store behavior. |
There was a problem hiding this comment.
Important
Two fail-closed gaps are worth resolving before these shapes are frozen: a mutation can commit a store that its own snapshot then rejects, and proven-new can take over a still-live child's alias. Details inline; two design questions and a nit below.
Reviewed changes
Reviewed the full 25-file, +4079/−0 diff at d94b0d1 — the second of three stacked PRs, adding the canonical agent-status store, the child-work record/admission contract, and the transport envelope. Ran the 7 new suites (45 pass), pnpm tc:node, and the changed-code quality gate (all clean). Most of the review went to the admission state machine and the store's commit/validate/persist invariants.
- Child-work vocabulary + codec (
agent-status-child-work.ts,-codec.ts) — one record owning all five kinds, astatevocabulary that can expressunverifiable, bounded invocation history, fail-closed parsing. - Admission state machine (
agent-status-child-work-admission*.ts) — identity is an Orca-mintedchildWorkId; aliases are keyed by parent/provider/segment/kind/aliasKind/alias and carry an invocation fence. - Store (
agent-status-store*.ts) — revisioned immutable state, clone-validate-commit mutations, tombstone removals, bounded snapshot persistence, and a replica that replays only contiguous same-epoch mutations. - Relay-context guard (
src/relay/agent-status-store-relay-context.test.ts) — asserts the shared core imports no main/renderer/electron.
ℹ️ Alias cardinality: a provider id still maps to one child per (parent, segment, kind)
The PR body says the provider-id alias "may legitimately point at more than one live run" and that a single-valued alias would be silently wrong. In this diff, serializeAgentChildWorkAliasKey keys aliases by parent/provider/segmentId/kind/aliasKind/alias only — childWorkId and fence are excluded — and the alias map holds exactly one childWorkId per key. A provider id therefore points at multiple children only when their segmentId (or kind/aliasKind) differs; two concurrent same-segment runs collide, and announce cannot represent both. Please confirm the producer always varies segmentId per concurrent run, otherwise the stated set-cardinality isn't actually expressible.
Technical details
# Alias identity is single-valued per scope
## Affected sites
- `src/shared/agent-status-child-work-alias.ts:137-159` — `serializeAgentChildWorkAliasKey` includes parent/provider/segmentId/kind/aliasKind/alias; excludes childWorkId and fence.
- `src/shared/agent-status-store-state.ts:132-147` — `validateAgentStatusStoreState` treats the alias key as unique, so one `childWorkId` per key.
- `src/shared/agent-status-child-work-admission-operations.ts:79` — a second concurrent binding with a different fence is rejected as `stale-invocation` under `current`.
## Required outcome
Confirm the producer always varies `segmentId` for concurrent same-provider-id runs (so two live children can coexist), or change the alias shape/key so one provider id can bind multiple children without relying on a segment side-channel.ℹ️ Replica adopts any different-epoch snapshot
applySnapshot only rejects a same-epoch non-advancing snapshot; any different-epoch snapshot is mirrored unconditionally. Mutation envelopes are strictly epoch-guarded, but a delayed or replayed predecessor-epoch snapshot will roll the replica back until the next snapshot arrives. Is epoch ordering enforced by the transport, or should the replica refuse a snapshot whose epoch it has already moved past?
Technical details
# Snapshot epoch is not ordered
## Affected sites
- `src/shared/agent-status-store.ts:115-128` — replica `applySnapshot` only guards same-epoch regressions; a different epoch always replaces state.
- `src/shared/agent-status-store.ts:141-148` — mutation replay is guarded by exact `envelope.epoch === state.epoch`, so the snapshot path is the looser one.
## Open question for the human
Does the transport guarantee snapshots are delivered at most once and in epoch order? If not, should a replica refuse a snapshot whose epoch is older than one it has already adopted?ℹ️ Nitpicks
adopt/resume/reparent/authorizeStoppassrequest.parentstraight intoagentStatusSubjectsEqual(agent-status-child-work-admission-core.ts:164), which throws on a malformed subject, whereasannounceparses and returnsinvalid. The parameter is typedAgentStatusSubjectso in-repo callers can't hit this, but if these become the untrusted ingress boundary, mirroringannounce's parse-and-reject would keep the failure mode consistent.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| const bindings = resolveAgentChildWorkAliasRecords(store, lookupAliases) | ||
| const exact = bindings.filter((binding) => agentChildWorkFencesEqual(binding.fence, fence)) | ||
| const exactIds = new Set(exact.map((binding) => binding.childWorkId)) | ||
| if (request.lifetime === 'proven-new') { |
There was a problem hiding this comment.
announce with lifetime: 'proven-new' skips the stale-binding guard the current path applies — it inspects only exact and never bindings. Because the alias key omits fence, a proven-new announce can silently move an alias off a still-live child onto a newly minted one, leaving the predecessor membership: 'live' but unreachable by alias; the identical input under current is rejected as stale-invocation.
Technical details
# proven-new can capture a live child's alias
## Affected sites
- `src/shared/agent-status-child-work-admission-operations.ts:55-81` — `current` fails closed when `bindings.length !== exact.length` (`:79`); the `proven-new` branch (`:58-78`) returns before that check and only inspects `exact` (`:59`).
- `src/shared/agent-status-child-work-alias.ts:137-159` — the key excludes `childWorkId` and `fence`, so `upsertAliases` (`agent-status-store-mutation.ts:153-169`) overwrites the prior binding.
## Evidence
1. `announce` a live child-1 with alias `T@inv1` -> accepted.
2. `announce` the same alias `T` with fence `inv2` and `lifetime: 'proven-new'` -> accepted, child-2 minted; alias `T` now resolves to child-2 while child-1 remains `membership: 'live'` / `state: 'working'` with no alias.
## Required outcome
Either `proven-new` must also fail closed when the alias already binds another child (`ambiguous` / `id-collision`) unless that predecessor is settled, or the rebind must settle/replace the predecessor so the store never reports an abandoned live child. If the producer is expected to settle the predecessor first, encode that expectation here.| moved, | ||
| aliases, | ||
| false, | ||
| oldAliases.map(serializeAgentChildWorkAliasKey) |
There was a problem hiding this comment.
reparent to the same parent is unconditionally store-rejected: the moved aliases keep the same parent, so their serialized keys equal the removeAliases keys passed here, and one mutation removes then re-adds each key at the same revision — tombstone.revision >= alias.revision (agent-status-store-state.ts:143) then fails validation. Skipping the removal when toParent equals fromParent (or removing only keys whose parent actually changed) fixes an idempotent reparent that currently errors.
d94b0d1 to
c1ac898
Compare
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between e544b9b2a0d538e2a1fd88df20463e1b3e76fdde and a90aacd. 📒 Files selected for processing (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review. 📝 WalkthroughWalkthroughThis change adds a shared agent-status store with strict codecs, mutation and snapshot contracts, persistence helpers, transport envelopes, tombstones, and authority or replica behavior. It adds child-work models, alias handling, admission operations, stop authorization, legacy projections, and freshness rules. Tests cover validation, mutation and transport behavior, admission edge cases, alias collisions, bounds, and relay use without Electron-specific imports. Priority: ⬇️ Low Merge Risk: 🟡 Moderate · up to Store consumers can receive rejected valid parent updates, reused child identities, or reverted replica state. Resolve these state-consistency issues before merging. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the purpose, scope, design decisions, testing, and hardening, but it does not follow the required template. It omits or leaves incomplete sections such as What Changed, Linked Issue with a populated Resolution Update the description to include every required template section. Add a valid linked issue after
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (2)
src/shared/agent-status-child-work-admission-core.ts (1)
33-45: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy liftAvoid repeated full-store snapshots in admission helpers.
getSnapshot()rebuilds and validates all five collections, performs full-store serialization, and deep-freezes the result. The admission paths invoke the helpers as follows:announceuses 2 calls per branch,adopt4,resume2,reparent3, andauthorizeAgentChildWorkStop1. The 14 source call sites therefore repeat O(store) work for child and alias reads.This is a real scalability cost in the shared admission contract, but the PR does not yet wire these operations to production consumers. Treat it as a recommended refactor, not a major runtime issue.
Add read methods that avoid snapshots. Use the child map for
getChild(childWorkId)and direct alias-key reads forresolveAgentChildWorkAliasRecords. Add a maintained child-to-alias index forgetAliasesForChild(childWorkId); the existing aliases map is keyed by alias key and cannot provide that lookup in O(aliases) by itself.src/shared/agent-status-store-status-codec.ts (1)
134-134: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winRebuild orchestration from validated top-level keys instead of spreading the input.
parseOrchestrationvalidates the known scalar fields and only checks thatattentionis a record, then returns{ ...value }.parseAgentStatusIpcPayloadCopyassigns that result toparsed.orchestration, andparseAgentStatusParentInputstores it as anAgentStatusIpcPayload. Unknown top-level orchestration properties therefore survive the canonical parent copy and violate the SAFETY invariant at line 243.The proposed change should whitelist the validated top-level fields. It does not establish a nested
attentionparser or a runtime failure from extra nested properties.♻️ Proposed shape for the return value
- return { ...value } + return { + taskId: value.taskId, + dispatchId: value.dispatchId, + ...Object.fromEntries( + optionalStrings + .filter((key) => value[key] !== undefined) + .map((key) => [key, value[key]]) + ), + ...(value.dispatchStatus !== undefined ? { dispatchStatus: value.dispatchStatus } : {}), + ...(value.attention !== undefined ? { attention: value.attention } : {}) + }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: df061c95-4e04-4c1e-8374-fc50f36be22c
📒 Files selected for processing (25)
src/relay/agent-status-store-relay-context.test.tssrc/shared/agent-status-child-work-admission-collision.test.tssrc/shared/agent-status-child-work-admission-core.tssrc/shared/agent-status-child-work-admission-operations.tssrc/shared/agent-status-child-work-admission.test.tssrc/shared/agent-status-child-work-admission.tssrc/shared/agent-status-child-work-alias.tssrc/shared/agent-status-child-work-codec.tssrc/shared/agent-status-child-work-freshness.tssrc/shared/agent-status-child-work-projection.test.tssrc/shared/agent-status-child-work-projection.tssrc/shared/agent-status-child-work.test.tssrc/shared/agent-status-child-work.tssrc/shared/agent-status-store-codec.tssrc/shared/agent-status-store-contract.tssrc/shared/agent-status-store-fact-codec.tssrc/shared/agent-status-store-mutation.tssrc/shared/agent-status-store-parent.tssrc/shared/agent-status-store-persistence.tssrc/shared/agent-status-store-state.tssrc/shared/agent-status-store-status-codec.tssrc/shared/agent-status-store.test.tssrc/shared/agent-status-store.tssrc/shared/agent-status-transport-envelope.test.tssrc/shared/agent-status-transport-envelope.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
| ...(input.firstObservedAt === undefined && previous?.firstObservedAt !== undefined | ||
| ? { firstObservedAt: previous.firstObservedAt } | ||
| : {}), | ||
| revision |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Keep parent firstObservedAt immutable.
When upsertParent updates an existing parent, an explicit input.firstObservedAt replaces the stored value. The analogous child update rejects such changes, and snapshot restoration preserves the stored timestamp. No supported update path requires replacing it, so this can corrupt canonical observation history.
Reject mismatches or always retain the previous value.
Proposed fix
const previous = state.parents.get(key)
+ if (
+ previous?.firstObservedAt !== undefined &&
+ input.firstObservedAt !== undefined &&
+ input.firstObservedAt !== previous.firstObservedAt
+ ) {
+ return false
+ }
const record = parseAgentStatusParentRecord({| if (subject.kind === 'pty' && status?.paneKey !== subject.paneKey) { | ||
| return false | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Find parent inputs built for `pty` subjects and check whether any omit `status`.
rg -nP --type=ts -C 8 'parseAgentStatusParentInput|AgentStatusParentInput|parent:\s*\{' src cloud | rg -n -C 8 "kind: 'pty'" || trueRepository: stablyai/orca
Length of output: 151
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- focused file ---'
cat -n src/shared/agent-status-store-parent.ts | sed -n '1,140p'
printf '%s\n' '--- relevant declarations and callers ---'
rg -n -C 5 --glob '*.ts' 'parseAgentStatusParentInput|AgentStatusParentInput|applyMutation|paneKey' src cloudRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -e
log=/tmp/coderabbit-shell-logs/shell-output-OF9tdJ
printf '%s\n' '--- saved log start ---'
sed -n '1,220p' "$log"
printf '%s\n' '--- exact symbol locations ---'
rg -n --glob '*.ts' 'parseAgentStatusParentInput|AgentStatusParentInput' src cloud
printf '%s\n' '--- PTY parent-like constructions ---'
rg -n -C 6 --glob '*.ts' "kind:\s*['\"]pty['\"]" src cloud | rg -n -C 6 'parent|subject|status|kind'Repository: stablyai/orca
Length of output: 24383
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- store contract ---'
cat -n src/shared/agent-status-store-contract.ts
printf '%s\n' '--- store codec ---'
cat -n src/shared/agent-status-store-codec.ts | sed -n '1,230p'
printf '%s\n' '--- applyMutation and parent usage ---'
rg -n -C 8 --glob '*.ts' 'applyMutation|parent\s*:' src | head -n 600
printf '%s\n' '--- focused parent tests ---'
rg -n -C 8 --glob '*agent-status*test.ts' 'parent|pty' src/shared | head -n 600Repository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- agent-status files ---'
git ls-files '*agent-status*' | sort
printf '%s\n' '--- applyMutation definitions/usages ---'
rg -n -C 12 --glob '*.ts' 'applyMutation' src/shared src/main src/renderer | head -n 500
printf '%s\n' '--- parent-specific tests ---'
for f in $(git ls-files '*agent-status*test.ts' | sort); do
if rg -q 'parent|parseAgentStatusParentInput|pty' "$f"; then
printf '%s\n' "--- $f ---"
rg -n -C 8 'parent|parseAgentStatusParentInput|kind:\s*['"'"'"'"'"']pty['"'"'"'"'"']' "$f" | head -n 300
fi
doneRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- store test helpers and parent tests ---'
cat -n src/shared/agent-status-store.test.ts | sed -n '1,190p'
printf '%s\n' '--- parent contract documentation ---'
rg -n -C 10 'parent|status|PTY|pty' docs/reference/agent-status-store.md
printf '%s\n' '--- mutation implementation ---'
cat -n src/shared/agent-status-store-mutation.ts | sed -n '1,260p'Repository: stablyai/orca
Length of output: 39307
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- PTY subject construction outside tests ---'
rg -n -C 8 --glob '*.ts' --glob '!*.test.ts' 'makePtyAgentStatusSubject|kind:\s*['"'"'"'"'']pty['"'"'"'"'']' src | head -n 500
printf '%s\n' '--- mutation calls outside tests ---'
rg -n -C 5 --glob '*.ts' --glob '!*.test.ts' '\.applyMutation\(' src/shared src/main src/relay | head -n 500Repository: stablyai/orca
Length of output: 304
Guard the PTY pane-key comparison when status is absent.
status is optional, but status?.paneKey !== subject.paneKey evaluates to true when a pty parent has no status. The parser returns null, so applyMutation rejects the mutation.
🐛 Proposed fix
- if (subject.kind === 'pty' && status?.paneKey !== subject.paneKey) {
+ if (subject.kind === 'pty' && status !== undefined && status.paneKey !== subject.paneKey) {
return false
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (subject.kind === 'pty' && status?.paneKey !== subject.paneKey) { | |
| return false | |
| } | |
| if (subject.kind === 'pty' && status !== undefined && status.paneKey !== subject.paneKey) { | |
| return false | |
| } |
| if ( | ||
| snapshotApplied && | ||
| snapshot.epoch === state.epoch && | ||
| snapshot.revision <= state.revision | ||
| ) { | ||
| return false | ||
| } | ||
| const mirrored = agentStatusStoreStateFromSnapshot(snapshot, snapshot.epoch) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect all snapshot application paths and any transport ordering guarantees.
rg -n -C5 --type=ts '\bapplySnapshot\s*\(|\bapplyTransportEnvelope\s*\(' src
rg -n -C5 --type=ts 'epoch|reconnect|snapshot|replay|sequence' src/relay src/sharedRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- agent-status-store symbols and implementation ---'
rg -n 'agentStatusStoreStateFromSnapshot|snapshotApplied|applySnapshot|applyTransportEnvelope|epoch|revision' src/shared/agent-status-store.ts
sed -n '1,220p' src/shared/agent-status-store.ts
printf '%s\n' '--- exact snapshot application bindings ---'
rg -n --glob '*.ts' 'agentStatusStoreStateFromSnapshot|applySnapshot\s*\(|applyTransportEnvelope\s*\(' src --glob '!**/*.test.ts' --glob '!**/*.spec.ts' | head -n 240Repository: stablyai/orca
Length of output: 8452
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions
Length of output: 30140
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- agent-status files ---'
git ls-files '*agent-status*' '*status*transport*' | head -n 160
printf '%s\n' '--- store construction and transport calls ---'
rg -n --glob '*.ts' --glob '*.tsx' 'createAgentStatusStore|applyTransportEnvelope|applySnapshot\(' src --glob '!**/*.test.ts' --glob '!**/*.spec.ts' | head -n 300
printf '%s\n' '--- transport contract and codec ---'
for f in src/shared/agent-status-transport-envelope.ts src/shared/agent-status-store-codec.ts src/shared/agent-status-store-contract.ts src/shared/agent-status-store-state.ts; do
if [ -f "$f" ]; then
echo "### $f"
sed -n '1,280p' "$f"
fi
doneRepository: stablyai/orca
Length of output: 10366
🏁 Script executed:
#!/bin/bash
set -u
printf '%s\n' '--- exact store construction and transport calls ---'
rg -n --glob '*.ts' --glob '*.tsx' 'createAgentStatusStore|applyTransportEnvelope|applySnapshot\(' src --glob '!**/*.test.ts' --glob '!**/*.spec.ts' || true
printf '%s\n' '--- relay and renderer agent-status transport files ---'
for f in \
src/relay/agent-status-store-relay-context.test.ts \
src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-replay.test.ts \
src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-hydration.test.ts \
src/renderer/src/hooks/ipc-events/agent-status-event-applicator.ts \
src/renderer/src/hooks/ipc-events/agent-status-ipc-bridge.ts \
src/renderer/src/hooks/ipc-events/agent-status-listeners.ts \
src/main/ipc/agent-status-ipc-boundary.ts \
docs/reference/agent-status-store.md
do
if [ -f "$f" ]; then
echo "### $f"
sed -n '1,320p' "$f"
fi
doneRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -u
printf '%s\n' '--- shared store files ---'
git ls-files 'src/shared/agent-status-store*' 'src/shared/agent-status-transport-envelope*' 'src/relay/*agent-status*'
printf '%s\n' '--- epoch and snapshot tests/docs ---'
rg -n -C4 --glob '*.ts' --glob '*.md' \
'predecessor|stale|replay|connection|incarnation|epoch|snapshot|applyTransportEnvelope' \
src/shared/agent-status-store* src/relay docs/reference/agent-status-store.md 2>/dev/null || true
printf '%s\n' '--- transport envelope and store codec/state definitions ---'
for f in src/shared/agent-status-transport-envelope.ts src/shared/agent-status-store-codec.ts src/shared/agent-status-store-state.ts docs/reference/agent-status-store.md; do
if [ -f "$f" ]; then
echo "### $f"
sed -n '1,260p' "$f"
fi
doneRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -u
printf '%s\n' '--- exact shared store paths ---'
git ls-files 'src/shared/agent-status-store*' 'src/shared/agent-status-transport-envelope*'
printf '%s\n' '--- relevant shared store tests and docs ---'
for f in $(git ls-files 'src/shared/agent-status-store*.test.ts' 'src/shared/agent-status-transport-envelope*.test.ts'); do
echo "### $f"
rg -n -C5 'epoch|snapshot|stale|replay|connection|incarnation|applyTransportEnvelope|applySnapshot' "$f" || true
done
for f in src/shared/agent-status-transport-envelope.ts src/shared/agent-status-store-codec.ts src/shared/agent-status-store-state.ts docs/reference/agent-status-store.md; do
if [ -f "$f" ]; then
echo "### $f"
sed -n '1,260p' "$f"
fi
doneRepository: stablyai/orca
Length of output: 44897
Reject snapshots from older authority incarnations. Replica applySnapshot rejects stale revisions only when the snapshot epoch matches state.epoch. applyTransportEnvelope forwards every snapshot envelope directly to it, and the snapshot envelope has no incarnation or generation field. A delayed epoch-a snapshot can therefore replace the replica state after it accepts epoch-b. Track the authority connection generation and reject predecessor snapshots before restoring state.
c1ac898 to
f144127
Compare
Review statusThe canonical store/child-work contract is clean after the hardening pass in Validation:
No in-scope findings remain. The consuming PR must bind A→B→delayed-A ordering to a trusted connection before enabling replica consumers; loss of contact remains |
|
The second one is not this branch's problem. It sits on The first one is from this branch's newer commits and needs fixing here. A fix for the identical violation is already proven on the child branch, so this should not need re-deriving. applied to both the function parameter and the Two things that cost time elsewhere in this stack, worth avoiding here:
|
e544b9b to
a90aacd
Compare
|
Follow-up: the first CI static-analysis run found a broad |
There was a problem hiding this comment.
Actionable comments posted: 3
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 171f46c0-49e0-4c37-b9e5-b2192e73ad5e
📥 Commits
Reviewing files that changed from the base of the PR and between f144127 and e544b9b2a0d538e2a1fd88df20463e1b3e76fdde.
📒 Files selected for processing (15)
src/shared/agent-status-child-work-admission-core.tssrc/shared/agent-status-child-work-admission-operations.tssrc/shared/agent-status-child-work-admission.test.tssrc/shared/agent-status-child-work-admission.tssrc/shared/agent-status-child-work-stop.tssrc/shared/agent-status-run-alias-index.test.tssrc/shared/agent-status-run-alias-index.tssrc/shared/agent-status-store-bounds.test.tssrc/shared/agent-status-store-contract.tssrc/shared/agent-status-store-mutation.tssrc/shared/agent-status-store-run-index.tssrc/shared/agent-status-store-snapshot-budget.tssrc/shared/agent-status-store-state.tssrc/shared/agent-status-store.test.tssrc/shared/agent-status-store.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/shared/agent-status-child-work-admission.test.ts
- src/shared/agent-status-child-work-admission.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
| state.tombstones.size <= AGENT_STATUS_STORE_LIMITS.tombstones && | ||
| state.revision - tombstone.revision < AGENT_STATUS_STORE_TOMBSTONE_RETENTION_REVISIONS |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Preserve unexpired child tombstones.
Remove one child. Then create 1,024 newer tombstones within fewer than 4,096 revisions. This capacity condition evicts the child tombstone. A later mutation can reuse the same childWorkId because upsertChildren checks only tombstone presence.
Do not evict unexpired child tombstones. Reject the mutation when the budget cannot preserve them, or maintain a separate bounded anti-reuse structure.
| expect(replica.getParent(parent)?.firstObservedAt).toBe(30) | ||
| }) | ||
|
|
||
| it.fails('does not roll a replica back to a superseded epoch snapshot', () => { |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Prevent replica rollback across epochs.
A replica accepts epoch-a, then epoch-b, and then accepts the delayed epoch-a snapshot again. This restores superseded state because different epochs bypass revision ordering.
Require an explicit epoch transition or an ordered generation fence. Then change it.fails to it.
There was a problem hiding this comment.
Important
The new tombstone compaction can evict a fresh, still-load-bearing child tombstone under size pressure, so a removed child id can be resurrected well inside the retention window the code claims to honor. Details inline.
Reviewed changes
Reviewed the delta since the prior pullfrog review (f144127 → e544b9b): two fix commits hardening the canonical store and the child-work admission contract. Re-ran the 9 affected suites (83 pass, 1 expected fail), pnpm tc:node, and the changed-code quality gate — all clean. Also reproduced the two remaining open threads against this head (proven-new can still rebind an alias off a live predecessor; reparent to the same parent is still store-rejected).
- Store read methods (
agent-status-store.ts) — addedgetChild/getAlias/getAliasesForChild/getRunAliasIndex; admission helpers read those instead ofgetSnapshot(), with a test asserting no snapshot is materialized per admission. - Aggregate byte budget (
agent-status-store-snapshot-budget.ts,agent-status-store-state.ts) —validateAgentStatusStoreStatenow rejects a state whose snapshot exceedsserializedBytes, closing the commit-then-throw gap; per-record byte lengths are memoized in aWeakMap. - Tombstone bounding + resurrection semantics (
agent-status-store-contract.ts,agent-status-store-mutation.ts,agent-status-store-state.ts) — cap lowered 16 384 → 1 024 with a 4 096-revision retention, size/age compaction on mutate and restore, and the parent tombstone guard relaxed to a revision comparison so a removed parent can be re-observed. - Invocation fences (
agent-status-child-work-admission-operations.ts) —resumerejects a non-advancing generation and retires aliases whose fence ages out of bounded history;announcerejects a fence mismatch on the current path. - Run-alias index (
agent-status-run-alias-index.ts,agent-status-store-run-index.ts) — per-alias run cap raised from 256 to the store's parent limit; the index is derived on demand and reconstructible from a snapshot. - Stop authorization extracted to
agent-status-child-work-stop.ts; store bounds tests added.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| function compactTombstones(state: AgentStatusStoreState): void { | ||
| for (const [key, tombstone] of state.tombstones) { | ||
| if ( | ||
| state.tombstones.size <= AGENT_STATUS_STORE_LIMITS.tombstones && | ||
| state.revision - tombstone.revision < AGENT_STATUS_STORE_TOMBSTONE_RETENTION_REVISIONS | ||
| ) { | ||
| break | ||
| } | ||
| state.tombstones.delete(key) | ||
| } | ||
| } |
There was a problem hiding this comment.
compactTombstones evicts the oldest tombstones whenever the count exceeds AGENT_STATUS_STORE_LIMITS.tombstones (1024), with no age check. The child-entity tombstone is the only unconditional resurrection guard (upsertChildren blocks on state.tombstones.has(...), while the parent/alias/fact checks are revision-gated and never block a later mutation), so a single 1025-entry removeChildren mutation can evict a just-created child tombstone and let that child id be re-added on the very next mutation — inside the 4096-revision retention window.
Technical details
# Size-pressure tombstone eviction drops fresh child tombstones
## Affected sites
- `src/shared/agent-status-store-mutation.ts:44-54` — `compactTombstones` deletes the oldest entries while `size > tombstones` regardless of `state.revision - tombstone.revision`, so it can evict a tombstone that is nowhere near the retention boundary.
- `src/shared/agent-status-store-mutation.ts:261` — compaction runs before `validateAgentStatusStoreState`, so the corrupted state is the one that gets validated and committed.
- `src/shared/agent-status-store-mutation.ts:171` — `upsertChildren` blocks resurrection only via `state.tombstones.has(agentStatusTombstoneMapKey('child', ...))`; parent (`:145`), alias (`state.ts:159`) and fact (`state.ts:170`) guards compare `tombstone.revision >= record.revision`, and a later mutation always has a higher revision, so those tombstones never block anything.
- `src/shared/agent-status-store-contract.ts:15` — `tombstones: 1_024`; `mutationEntries: 2_048` allows one mutation to add up to 2048 tombstones.
## Evidence (reproduced on e544b9b2a0)
1. `applyMutation({ parent })`; `applyMutation({ children: [child-1] })`; `applyMutation({ removeChildren: ['child-1'] })`.
2. `applyMutation({ children: [child-1@observedAt:30] })` → `null` (guard holds).
3. `applyMutation({ removeChildren: [1025 unused ids] })` → non-null; compaction drops `child-1`'s tombstone (and one unused) to get back to 1024.
4. `applyMutation({ children: [child-1@observedAt:30] })` → non-null; `getChildren(parent)` shows child-1 resurrected with stale state.
A 1025-entry `removeChildren` is well within `mutationEntries`; the existing `agent-status-store.test.ts:347` only exercises the no-pressure path.
## Required outcome
A mutation must not evict a tombstone whose guard is still load-bearing. Either reject a mutation that would exceed `AGENT_STATUS_STORE_LIMITS.tombstones` (fail closed instead of compacting on size), or evict only age-expired tombstones and reject when the cap cannot be respected. Add a test that overflows the cap while a fresh child tombstone exists and asserts the re-add still returns `null`.
## Note
The restore-time loop at `agent-status-store-state.ts:257-262` deletes size-blindly too, but it is also age-gated, so a restored snapshot can drop child tombstones older than the retention window. Decide whether that matches the intended restore semantics.…tablyai#20717) * feat(agent-status): add canonical shared store contract * fix(agent-status): harden canonical store invariants * fix(agent-status): close canonical store race windows


ELI5
Adds the new store's contract — the canonical row shape, the child-work record, and the transport
envelope — as new files. Nothing imports them yet. Pure addition: 25 files, +4079, zero deletions.
Why this exists
This is the contract the rest of the migration is built against: a status row keyed by an
Orca-minted
runIdrather than by its pane, with the provider's own session id kept as an alias thatmay legitimately point at more than one live run.
That alias is a set, not a single value, and that is not a style choice — it was measured. Two
concurrent
claude --resume <same id>executions both report that id and write divergent branches, soa provider id does not uniquely name a live agent. A single-valued alias would be silently wrong on
exactly that case.
It also lands Amendment A's child-work record: one collection owning all five kinds
(
agent | workflow | command | monitor | unknown), each child keyed by a host-mintedchildWorkId.The earlier design kept an agent-only canonical collection plus a separate background-task state —
but the chat strip renders agent-kind tasks too, so that split would have represented the same task
canonically twice.
What a reviewer should check first
Whether these are the shapes you want frozen, since three later PRs build on them — particularly the
alias-set cardinality and the child-work state vocabulary, which must be able to express
unverifiableso a child on a host we cannot reach is never reported as idle.Second: this PR's ablation is weak by nature. Reverting brand-new modules makes their suites fail to
import, which proves the tests exercise the code but little else. There is no prior behavior to ablate
against in a contract-only change; the real test is the PR that consumes it.
Scope
Second of three, stacked on #20716. Nothing consumes these types yet — that is the next PR.
Post-review hardening
The review pass added focused reliability fixes without adding consumers: delayed observations are fenced after resume, bounded invocation aliases can be safely reused, snapshot admission accounts aggregate UTF-8 bytes with immutable-record caching, and batch child removal cleans aliases in one pass.
Validation at commit
a90aacd83e: 9 focused contract suites passed (83 tests plus 1 intentional expected-failure for the deferred epoch-ordering integration gate),pnpm tc:node, changed-code quality, formatting, and pre-commit checks passed; selective ablation made the four new regression tests fail when the corresponding production fixes were reverted, then pass after restoration. The all-new-files-reverted arm only reports missing test files because this PR intentionally has no production consumers yet.The remaining integration gate is binding A→B→delayed-A ordering to the trusted connection before the consuming PR wires these modules; loss of contact remains
unverifiable, never death.