carlos / platform Public

Implementation review: durable team-service prototype closed approved

On branch team-service-prototype

Claimed by codex~paul@keymail.dev 3 weeks ago

Opus is independently reviewing the committed implementation against the merged design. Code tip b96bd586, brief at d5c98b80 in docs/superpowers/reviews/CODEX-REVIEW-BRIEF-team-service-prototype-R1.md. Local build/vet and both package race tests passed; full Amadan CI passed on d5c98b80. Review pending; no live access or production changes.

Verdict: NOT READY. There is one P1: a job can set its own price table, which switches off the account's currency cap. There are six P2s and some P3s.

I read every changed source and test file in internal/team and internal/teamcontract, plus the budget and recovery sections of the spec and plan. Per the brief I did not run any tests or commands, so the "tests pass" claim comes from the brief, not from me. Tracing them by hand, I found no expectation that looks wrong.

P1

P1-1. A later job (or child job) can disable the account's currency cap by choosing its own price table

  • Fault family: account/parent policy inheritance and the reservation ledger. This is the same family as the "per-job account-cap escalation" development check, which is not counted as a review round.
  • Evidence: - jobs.go:130: CreateJob compares only spec.Policy.Account with the first job's policy. Rates and PerCall are never compared. - policy.go:99: Validate accepts prices of zero. - budget.go:98: reserve prices with the job's own policy (j.Policy.price). The cost of every reservation therefore comes from the proposing job's rates. - budget.go:73-87: the account check adds that self-priced cost to the account total. - budget.go:144: settle records the receipt's usage with no comparison against what was reserved.
  • Scenario: 1. Job 1 sets the account policy: DefaultPolicy(300_000, testRates()). A full call then reserves 157,000µ, so the 300,000µ cap allows about one full call. 2. Job 2 copies the same Account limits, so jobs.go:130 accepts it, but uses Rates{Version:1} with every price at zero. 3. Each of job 2's provider intents reserves 0µ. The account check passes until settled spend has already crossed the cap. Calls and tokens are still capped (24 calls, 200k/40k tokens), but currency is not. 4. 24 concurrently reserved calls at real prices come to about 3.77M µ, roughly 12 times the "hard" cap. 5. A child job can do the same against its parent's Job.CostMicros, because checkBudget uses the same self-priced value.
  • Why it matters: the plan says "The first job fixes an account's budget … subsequent job proposals cannot increase them." The spec says "reserve those per-call ceilings at the configured prices" and makes the currency cap the hard financial bound. The teamcontract witness test only covers the call count.
  • Minimal fix: - In CreateJob, refuse a policy whose Rates or PerCall differ from the account policy's (this also covers children). Alternatively, have reserve price with the account policy's Rates. - Add a teamcontract test: a second job with zero rates cannot reserve past the account currency cap. - Optionally, refuse zero token prices in Validate.

P2

P2-1. An unknown outcome can release its reservation for free

  • Fault family: unknown outcomes and budget.
  • Evidence: actions.go:508-511 treats a read-only or idempotent action as replayable even when the adapter gave no definitive answer, including when Reconcile returned an error. - If the job has finished, actions.go:540-548 revokes the action and releases its reservation. - If it has not, actions.go:550 puts the action back to intent, and a later cancel (jobs.go:472-479) releases it. - A receipt that arrives late is then refused (actions.go:373-374).
  • Why it matters: the plan (lines 99-100) says unknown usage is "never silently released as free capacity".
  • Reachability: not reachable with the fixture adapters. FakeTracker.Reconcile always answers definitively (fixture.go:392-399). The test comment "replays without a definitive answer" (actions_test.go:186) actually takes the definitive-absence branch.
  • Fix: only a definitive absence may revoke or release. An idempotent replay without a definitive answer should keep the reservation open and the action in flight. Cancel should report it as in flight, not revoke it.

P2-2. Reconcile and Resume can act on an action whose Execute is still running

  • Fault family: dispatch boundary and lost replies.
  • Evidence: - actions.go:493 accepts dispatching actions in the current process. Only the doc comment limits this to "after a restart". - Resume has no "only while paused / once per run" guard (recovery.go:33-41, :98). - A replaced Store's in-flight Execute hits the same race when the new owner runs Resume.
  • Scenario with FakeForge: 1. Admit commits. 2. A concurrent Reconcile gets a definitive absence and moves the action back to intent. 3. The live Execute publishes, then Record is refused (CodeState) and the receipt is dropped. 4. Calling Dispatch again publishes a second time on a non-deduplicating "reconcilable" forge.
  • Related: Dispatch calls Lost with the caller's possibly-cancelled context (actions.go:463), which can leave actions stuck in dispatching.
  • Fix: - Record the admitting incarnation on the action, and refuse to reconcile a dispatching action admitted by the current one. - Refuse Resume unless admission is paused. - Call Lost with context.WithoutCancel.

P2-3. One irreconcilable lost reply can quarantine the store forever

  • Fault family: recovery liveness.
  • Evidence: - Quarantine only clears when no action is unresolved, across every job including cancelled ones (recovery.go:152-158). - FakeProvider.Reconcile is never definitive (fixture.go:279-283). - SettleAudited leaves the action uncertain (budget.go:220; asserted at budget_test.go:151-155). - After an audited settlement, Record is refused (budget.go:162-163, reached from actions.go:376).
  • Scenario: a provider reply is lost, then the process crashes uncleanly. The store stays paused for every account. The only way out is to fabricate a receipt before auditing, which is undocumented.
  • Fix: either have the audited settlement move the action to a terminal "charged, unresolved" state that no longer blocks, or exclude audited and finished-job actions from the quarantine condition.

P2-4. Concurrency caps ignore attempts that are still pending containment

  • Fault family: concurrency and containment.
  • Evidence: - scheduler.go:154-157 counts only active and stopping attempts. - Resume turns lapsed attempts into expired while containment is still pending (recovery.go:144). - Complete and Release leave attempts pending containment (scheduler.go:305, :346).
  • Scenario: with an account cap of 2, two workers are running and the store restarts. Resume marks both expired, and two new claims then succeed. That gives four workers the supervisor has not confirmed stopped. The code's own comment says "expiry is not proof the worker stopped" (scheduler.go:115-116).
  • Fix: count every attempt with containment='pending', whatever its state.

P2-5. A successful Conclude leaves child jobs and open intents running

  • Fault family: termination and descendants.
  • Evidence: evidence.go:276-279 uses bumpJob, not terminate. Children are only stopped inside terminate (jobs.go:495-519).
  • Scenario: the parent ends succeeded while a child keeps claiming and spending. Intents left on the parent keep their reservations open for good.
  • Fix: refuse Conclude while non-terminal children exist (or terminate them), and revoke open intents on success.

P2-6. Any step can publish to the forge, including the reviewer

  • Fault family: capability boundary.
  • Evidence: Intend (actions.go:140-216) and Conclude (evidence.go:377-395) never check the step's capability against the operation. actions_test.go:63,74 successfully publishes from a review attempt.
  • Scenario: a candidate is published before review or verification, by an attempt the spec describes as read-only.
  • Fix: add a closed capability-to-operation table (OpForgePublish only for CapPublish) and check it in Intend.

P2-7. A restored-snapshot quarantine clears without checking intents

  • Fault family: startup recovery.
  • Evidence: recovery.go:152-163 clears quarantine when nothing is uncertain. For a restored snapshot (store.go:294-295), rows still at intent may have been dispatched after the backup, and Dispatch will run them again. That is a duplicate paid call for the unsafe provider class.
  • Fix: while quarantined because of a restore, reconcile every non-terminal action by key, or keep the store quarantined until an operator acts.

P3 (record for follow-up; none of these reopen the review)

  • Evidence trust: - The independence check uses provenance strings the caller supplies, not the attempt's runner (evidence.go:168, :192-200). - Check results are self-reported, and the candidate's TestsRun is never compared with the base result's. - This is acceptable as trusted fixture provenance, but must be bound before the network transport exists.
  • Registration vs conclusion mismatch: registration validates against latestAny while Conclude uses latestArtifact. A failed rework can make the evidence unsatisfiable. This fails closed.
  • Unresolvable wait reasons: Release accepts approval, budget and uncertain reasons, but nothing exists to resolve them, so the job stays parked until cancelled. The spec prefers refusing unsupported cases.
  • Job time cap: JobSeconds is only enforced at Claim.
  • Over-reservation settlement: settling above the reserved amount is recorded silently.
  • Canonical payloads: numbers spelled differently (1 vs 1.0) produce different hashes, contrary to the doc comment. This fails closed with a conflict.
  • Missing crash tests from the M1 acceptance list: crash after the receipt but before Record, and crash before the outbox acknowledgement. There is no witness for "restored snapshot, not revoked".
  • Business fixture coverage: it does not test excluding sources from failed attempts, a reconciliation that mismatches the collected sources, or a stale review after the reconciliation changes.

Development fixes I checked against the source

  • Strict-JSON trailing bytes: fixed (jobs.go:526-545, also used by canonical).
  • Duration overflow: fixed (policy.go:108-113). The admission window is also capped at 5 seconds.
  • Parent depth escalation: fixed (jobs.go:143, checks both policies; MaxDepth ≤ 1).
  • Per-job account-cap escalation: fixed for the limits themselves (jobs.go:130, budget.go:81) but not for the price table (P1-1).
  • Descendant cancellation: fixed. terminate cascades in the same transaction (jobs.go:495-519), and this also covers revocation and attempt exhaustion.
  • Stale Store ownership: fixed. Every transaction re-checks the incarnation (store.go:368-378), so an old Store cannot Resume, Close, read or write. Only adapter calls that are already running escape this; see P2-2.

The remaining contracts held up when I traced them: fencing and leases (no grace period after expiry), revision-checked admission, cross-account scope refusal, failing closed on unknown kinds, skipped, compile-error and zero-test check results never satisfying the predicate, and parent/child ledger aggregation.

NOT READY (P1: P1-1).

R1 fixes are committed at 06b09463423d0a58a38210779d826a8f41a58a44; the R2 brief is e2112ac54be6f400e8456c2d7e2eb5a757f40275. Opus R2 is running on the user-selected pabqas@gmail.com Claude account. Implementation review budget: R1 NOT READY (one P1, seven P2); R2 pending, maximum three rounds. The earlier accepted Fable design review is separate and closed.

P1-1: freeze account Rates and PerCall; reserve with the canonical account policy. Internal and external witnesses reject zero-price later/child jobs. P2-1: no automatic redispatch once admitted. Missing effect evidence never releases potentially billable usage; retain the reservation until receipt or conservative audited charge. P2-2: persist admitting incarnation; refuse reconciliation of a current dispatch; serialize Resume and require paused admission; record dispatch outcome despite caller cancellation. P2-3: audited unknown usage no longer quarantines unrelated jobs. Its action outcome remains unknown. P2-4: every uncontained attempt holds a concurrency slot. Expiry compares parsed timestamps, not variable-width RFC3339Nano text. P2-5: wait for children and containment before conclusion; successful termination revokes unused intents. P2-6: only publish-capability attempts can publish to forge/tracker; success requires a receipt from that capability. P2-7: schema 2 adds an external transaction position; same-incarnation rollback is detected. Missing/restored history remains quarantined across reopen, including snapshots with no surviving action records. No operator override is implemented in this prototype.

Both packages passed ordinary tests and race tests. The updated fixture recovers a publication receipt after a crash before Record. Full CI is rerunning on the branch tip.

P3 follow-ups retained before live work: authenticated evidence/check counts, failed rework consistency, waiting-state resolution, elapsed job cap beyond Claim, adapter request ceilings and reporting over-reservation usage, numeric canonicalization, further crash/outbox witnesses and business-fixture negative cases. No live adapter or production operation is included in this branch.

I've checked all eight R1 findings against the source and am writing up the result. Here are the round 2 findings for the parent to record.

---

Implementation review R2 of 3 (Opus, independent): READY AFTER FIXES

I read all of internal/team that the fix diff touches, plus jobs.go, scheduler.go, policy.go, the regression tests and the teamcontract witness. I made no edits and ran no commands or tests, so "tests pass" rests on the brief.

There are no P1s and one new P2. That P2 is in the same fault family as R1 P2-7 (startup recovery), so the brief's two-round rule applies: it goes to the AGENTS scope/enforcement decision, not a third patch loop. This round has no P1, so review stops here.

R1 disposition

  • P1-1 (job-chosen prices): resolved. - jobs.go:133-135 refuses any Rates or PerCall that differ from the account policy. This covers child jobs too, because the check runs before the parent branch. - budget.go:98-111: reserve prices and caps each reservation with accountPolicy. reserve has one caller, Intend (actions.go:200). - checkBudget (budget.go:50-88) checks the parent chain's job limits against amounts priced at the account rates. - Witnesses: review_regression_test.go:667 and the independent teamcontract/authority_test.go:71.
  • P2-1 (unknown outcome released for free): resolved. - Reconcile without a receipt now always goes through Lost and stays uncertain (actions.go:509-527). There is no path from an admitted action back to intent or revoked. - Cancel only revokes intent rows (jobs.go:475-485). - Record accepts uncertain rows whatever the job's state (actions.go:375). - A restored intent becomes uncertain in the same transaction that detects the restore (store.go:344-347). - Witness: TestEveryReplayClassRetainsUnknownUsage.
  • P2-2 (acting on a live dispatch): resolved. - admitted_incarnation is persisted (actions.go:338). Reconcile refuses a dispatching action from the current incarnation (actions.go:492). - Resume is serialized by recoveryMu and requires paused admission (recovery.go:34-50). Admission can only reopen through Resume, so no live dispatch can overlap a Resume in the same incarnation. - Lost and Record now get WithoutCancel (actions.go:466,471). - Owner change: the new owner may reconcile the old owner's in-flight action. With no redispatch, the worst case is the old owner's Record being refused as stale and the action staying uncertain with its reservation open, which is conservative.
  • P2-3 (permanent quarantine from one lost reply): resolved for the store-wide blocker. recovery.go:120 excludes settled_audited rows, and the action stays uncertain. What remains is P3 (b) below.
  • P2-4 (concurrency ignores uncontained attempts): resolved. - Claim counts every containment='pending' attempt (scheduler.go:154,157), and so does Conclude (evidence.go:251). - Recovery compares parsed deadlines (recovery.go:152-176). - No SQL text comparisons of timestamps remain (I grepped for them).
  • P2-5 (success leaves children and intents open): resolved. Conclude refuses unfinished children (evidence.go:257-263) and ends through terminate (:284), which revokes intents and releases their reservations. Witness: TestConcludeRevokesUnusedIntents.
  • P2-6 (any step can publish): resolved. - operationAllowed (model.go) is checked in Intend (actions.go:170) before the existing-key/rebind branch, so reusing a key cannot get round it. - The success query also filters on CapPublish (evidence.go:384). - A step's capability can't change after creation, so Admit doesn't need to check it again.
  • P2-7 (restored snapshot clears quarantine): resolved as specified. - The marker position check catches a restore within the same incarnation (store.go:315-323). - The restore_uncertain flag is never cleared (store.go:307, recovery.go:182), as the plan states. - The new mechanism adds the P2 below.

New findings

P2-A. A crash just before a transaction commits is treated as a restore, which quarantines the store permanently

  • Fault family: startup recovery / restore detection. This is the same family as R1 P2-7, so the two-round rule triggers.
  • Evidence: - transact writes the external marker with revision R+1 (store.go:442, via writeMarker's rename at :397) before tx.Commit() (:446). - start does the same at :337, before its update commits. - On reopen, any revision mismatch sets restore=1 (store.go:319-320). - restore_uncertain is never cleared, so Resume always stays quarantined (recovery.go:182). - Every remaining intent row is turned into uncertain (store.go:344-347).
  • Scenario: 1. The process is killed (SIGKILL or OOM, i.e. local process recovery, which the brief puts in scope) after the marker rename but before SQLite commits. 2. The window exists on every call, reads included (GetJob, Ledger), and during Open itself. 3. On reopen, marker = DB+1, so the store reports "restored snapshot". 4. Admission stays paused for every account, permanently. There is no override API. 5. The intents of an ordinary crash also become uncertain and keep their reservations open. 6. Nothing unsafe happens, but an ordinary crash makes the store permanently unusable. The plan says ordinary crash recovery should reopen admission.
  • Minimal fix: - Commit first, then write the marker. - At start, treat "DB exactly one revision ahead of the marker, same incarnation" as an unclean shutdown. Treat DB behind the marker, or any other mismatch, as a restore. A restore can never make the database newer than its witness, so this is unambiguous. - If the marker write after commit fails, mark the Store as broken and refuse every further transaction, so the database can never get more than one revision ahead. - Apply the same ordering in start. - Add a fault-hook witness: crash between commit and marker write, then reopen as an unclean shutdown that resumes. - Alternatively, record this crash window as a known limitation, but per the brief that is the scope decision, not a patch.

P3 (follow-up list)

  • (a) Dispatch looks up the adapter only after Admit commits (actions.go:456-463). - If the adapter is missing, the action is left dispatching in the current incarnation. Reconcile refuses it (:492) and so does SettleAudited (budget.go:218-223). - After a restart, the adapter error is not ErrUncertain, so it aborts the whole of Resume (recovery.go:139-145). - This needs a misconfigured Options.Adapters. Fix: resolve the adapter before Admit.
  • (b) An audited uncertain action keeps its job waiting. - The job stays in WaitUncertainOutcome (actions.go:409), and a late receipt after the audit is refused (budget.go:166-167). A real publication therefore can never count as evidence. - It fails closed, and Conclude/Cancel still end the job. This belongs with the existing "unresolvable wait reasons" follow-up.
  • (c) A restore can reuse the previous incarnation number. start derives the next incarnation from the database alone (store.go:329). After restoring a snapshot from an older incarnation, the new owner can get the same number as a still-live old handle, which then passes the ownership check (store.go:418-425). Admission stays quarantined, so the impact is small. Fix: next = max(dbInc, markerInc) + 1.
  • (d) quarantine_why grows on every quarantined Resume, which re-appends "; N actions unresolved" (recovery.go:183,187). Cosmetic.
  • (e) Schema 1 migration quarantines permanently. A v1 marker has no revision, so readMarker fails and restore is set (store.go:318). Every migrated v1 store is therefore permanently quarantined. This matches the plan's wording ("quarantines its history"); the follow-up list should say so explicitly.

Claims and witnesses

  • The publication crash witness genuinely exercises Execute → crash → recovery of the receipt with no second dispatch.
  • The same-incarnation restore witness keeps the newer marker, as the brief says.
  • The narrowed claims in the plan diff match the code: no redispatch, the audited-settlement liveness, the sticky restore quarantine with no override, and reads advancing the position.
  • No witness covers the commit-window crash in P2-A.

READY AFTER FIXES (P2: P2-A). P2-A repeats R1 P2-7's fault family (startup recovery), so per the brief it goes to the AGENTS scope/enforcement decision rather than a third patch loop.

Paul selected the central invariant option: “Fix the recovery ordering with one guard and a crash-boundary test (recommended).” Proceeding with that scoped P2-A fix. Broad implementation review stopped at R2 without P1; the required storage-behaviour check will use the remaining third-round slot. No live integrations or production changes.

The approved R2 P2-A fix is c44ec92b7adc6de80a0d16a492e88044efa2574a; the focused storage-check brief is cb280f78152020fb854e4689ee232453eb70b440.

One process-shared guard serializes the database commit and following witness publication, including replacement handles. Failed commit/witness writes poison that handle. Startup repairs exactly one unpublished commit before advancing, including interrupted first/repeated Opens. Other mismatches retain restore quarantine. Normal transactions check current owner and witness equality; the next owner exceeds both stored and witnessed incarnation numbers.

Validation: real child-process exits before commit reproduced the original permanent quarantine for both normal transactions and startup. All new process-crash cases now pass, including consecutive crashes and first Open. Tests also cover a real witness I/O failure, refusal to use the damaged handle, recovery after reopen, and exclusion of a competing Open until witness publication. Both packages pass race tests. Package cross-builds pass on Windows amd64, macOS arm64 and Linux arm64. The changed packages remain outside the root-binary census.

Opus is checking only this changed storage behaviour, using slot 3 of the existing review budget. Broad review stopped at R2 without P1. Full branch CI is running; no further user decision is pending.