Repository navigation
Phase A2: Allocation ledger and owner policy - #2032
Conversation
📦 Package PreviewYour package is ready to test! bun install -g nemar-cli@PR2032Version: 🤖 Updated on each push. |
5c7246b to
94b1bc9
Compare
|
Review triage, driver, 2026-11-04. Round 1 was a three-reviewer panel (contract and types, tests and errors, comments and simplification) plus the Opus checkpoint the issue requires; round 2 was the Opus delta on the fix commits. Every accepted finding is fixed on this branch and was re-verified against its test. Deferred or open, with the reason:
Open for the repository owner: whether a refund or a charge correction credits the |
941ba78
into
feature/issue-2005-epic-compute-core
Phase A2 of the compute program (epic #2005, issue #2007): NEMAR can say how many service units (SU) a holder may spend and refuse a spend that would exceed it, atomically. This body describes the branch as it is after the round-1 and round-2 review fixes.
What the branch adds
0114_compute_ledger.sql:compute_policy(one immutable row per version),compute_pools(per holder and pool, with the four platform pools seeded) andcompute_ledger(the eight entry kinds, append-only). Every CHECK is named and TRUE or FALSE, every GLOB is at most 50 characters, and there is no foreign key.compute_ledger_applyadds an entry's deltas to its pool and its held and charged deltas to its budget pool. A test reads every source file and migration for any other write of a total.backend/src/services/compute-ledger.ts:ensurePool,holdStatementsandplaceHold(one conditional INSERT,meta.changesas the winner test, caller guards throughextraGuards),releaseHold,settleProvisional(achargeand anyoverrunin one statement),settleFinal,refundJob,grantPool,adjustPool,expireUnused,availableMilli. Every statement is exported as*_SQL.backend/src/services/compute-policy.ts(strict read that fails closed, owner-only audited write) andbackend/src/routes/admin/compute.ts(policy and pool routes,{ error, code }refusals, anIdempotency-Keyon every write, an audit row per write).shared/contract/compute-admin.ts(error words, request cap, open response schemas only) andnemar admin compute policy show|setandpool show|grant|adjust..context/compute-program/implementation-notes.md.Round-1 fixes (Opus checkpoint and the review panel)
settleFinalafter a refund isrefunded(a NOT EXISTS term inFINAL_INSERT_SQL).adjustonly when it carries a job, forbids a granted delta on a job-scoped adjust, andFINAL_INSERT_SQLno longer skips a zero difference, so the keyjob:<id>:finalalways records it.peoplepool of the same word and a platform pool names none (compute_ledger_budget_is_people), and a hold, release, charge, overrun and a job's final-settlement adjustment on an account or partner pool must name it (compute_ledger_budget_required).INSERT OR IGNORE,OR FAIL,OR REPLACEand a multi-row INSERT ... SELECT: no total leaves 0 to 2^53 - 1 (compute_ledger_totals_in_range), a hold does not take available below 0 (compute_ledger_hold_fits), and a release or charge names a hold of the same job, pool, budget and held amount (compute_ledger_closes_its_hold). The migration header and the ADR state the two caveats the database cannot prevent (REPLACEskips the append-only DELETE trigger on D1;DROP TABLEremoves the triggers and a rebuild must copy rows before creatingcompute_ledger_apply).INSERT OR <x>into the ledger, anyUPDATE [OR x]of the pools that names a total in any quoting, schema or escaped-quote spelling,REPLACEandDELETEon either table, and any second trigger oncompute_pools; 36 planted spellings must each fail it and the legitimate statements must pass.insufficient_balanceunless the caller passed a guard (guard_refused); an adjustment naming a budget that is not there ispool_not_found.replayOrConflict; an administrator's key is stored asgrant:<actor>:<key>andadjust:<actor>:<key>; a caller's key may not start withjob:orhold:.replayed: truewith the closing entry) andhold_closedsays whether a release or a settlement closed the hold (closedBy); a hold takes no key of its own, its key isholdKey(jobId)(job:<id>:hold).*_SQLstatement is checked with EXPLAIN QUERY PLAN (aliases resolved) for a scan ofcompute_ledger;FINAL_INSERT_SQLandJOB_CHARGE_SQLnow usecompute_ledger_closes_onceandcompute_ledger_job.account_not_found); its pools are still read and its grant corrected, for the record. The policy write requires an owner that is not deleted and is in an active status.would_exceed_limit, and one request may move at most 2^40 milli-SU (both chosen: the cap isCOMPUTE_REQUEST_MILLI_MAX, and the overflow guard stays for a long run of grants).guard_refusedin the refusal codes with its status,COMPUTE_LEDGER_REASONSinshared/compute-state.ts,HoldRefusalderived byExtract,COMPUTE_PLATFORM_KEYSused by the route and the CLI, drift tests for the holder kinds and the platform keys, and ADR decision 10 namescompute-admin.ts.computeErrorCodeand its pin,MAX_MILLI, the holder-kind aliases, the route'sMAX_SAFE,zodFields),issuesOf(error, prefix?)is the one copy, and a behaviour test checks every schema ofcompute-admin.tsaccepts and keeps unknown keys at every depth.PUT /compute/policyanswers 403owner_onlyfor an administrator before the body is read (an invalid and a non-JSON body expose no field list), pinned by test.holder_refandactor_user_idare phase A7's (Phase A7: Tenant reconcile, observer and reporting #2012) with its own migration, and the CLI says a re-run is a new request.Round-2 fixes
placeHoldof a job whose hold was released or settled returned{ ok: true, replayed: true }while the pool'sheldwas 0, so a caller could believe the job still held SU and a later settle washold_closed. It now returns{ ok: false, code: "hold_closed", closedBy: "released" | "settled" }and writes nothing; an open hold replayed is still{ ok: true, replayed: true }, and a closed hold asked for with a different request is still anidempotency_conflict. Tests: hold, release, same hold again; hold, settle (under, equal and over the hold), same hold again; an open replay unchanged; the conflict first; and the seeded random sequences replay every hold of the run and expect the open or closed answer by the ledger.compute_ledger_budget_requiredrequired every refund and every pool-level charge correction on an account or partner pool to name thepeoplebudget, which is option B, although ADR 0118 and the migration header say the schema does not decide it. It now requires a budget only where both options agree: a hold, a release, a charge, an overrun and a job's final-settlement adjustment. A refund and an adjustment of a charge that names no job may name thepeoplebudget or none;compute_ledger_budget_is_peoplestill refuses any other budget when one is named. The migration tests run both choices on bun:sqlite and on Miniflare D1, and the five required kinds are still refused without a budget.peoplebudget records consumption only and a refund or a correction moves the person's pool alone; option B, they also credit it back. The code is unchanged and is option B, with the interim owner-only rule for an account's charge correction; a test fails if a refund stops naming the budget. If the owner chooses option A the code changes and the migration does not.Migration 0114 constraint and trigger changes since round 0 (the migration is unmerged and edited in place)
compute_ledger_deltas(anadjustwith a job carries charged only, which may be 0; anadjustwithout one is exactly one of granted or charged) andcompute_ledger_budget_kinds(an adjustment that carries a job may name a budget).compute_ledger_closing_hold(the closes-its-hold trigger answers first for every row it covered) andcompute_ledger_budget_distinct(the budget trigger answers first);compute_ledger_budget_platformis replaced bycompute_ledger_budget_is_peopleandcompute_ledger_budget_required.compute_ledger_totals_in_range,compute_ledger_hold_fits,compute_ledger_closes_its_hold,compute_ledger_budget_is_peopleandcompute_ledger_budget_required(the last is narrowed in round 2). Triggers now: 13 (apply, budget_is_people, budget_required, closes_its_hold, hold_fits, no_delete, no_update, pool_exists, totals_in_range on the ledger; no_delete and no_update on the policy; identity_fixed and no_delete on the pools).Gates
Round 2, head
ff50df04(a fast-forward of the rebased round-1 head94b1bc9f, which sat on the epic branch after A1b,7ba7d2f1):bun testcommand: 326 pass, 0 fail (8 files).backend/test/compute-ledger-rules.test.ts, the table-rule tests insidecompute-ledger-migration.test.ts) with the words and contract tests (test/compute-admin-contract.unit.test.ts,compute-state.unit.test.ts,contract-schemas.test.ts,compute-contract.unit.test.ts,compute-header.unit.test.ts): 639 pass, 0 fail (6 files).bun run migrations:d1-check(run alone): "All migrations applied on real D1." and "Catalog matches bun:sqlite (178 objects, 51 tables). OK." (the five new BEFORE INSERT triggers and the reworked constraints all run on D1; the table-rule tests also run on Miniflare D1).bun run typecheck: no errors.bunx biome checkon every file this branch touches: no errors (7noExplicitAnywarnings in test files).bunx biome check src shared backend/src: "Found 5 errors. Found 1 warning." The five errors arenoUselessElseinbackend/src/services/zenodo.tsand the warning is inbackend/src/services/doi-orcid-discovery.ts; neither file is touched by this branch.bun testis the driver's to run; the one failure it had before this round wastest/account-copy-parity.test.ts, which compares against a drifted sibling website checkout and is unrelated.Mutation checks
About 260 single-line mutations were applied one at a time and each run stopped at its first failing test: the migration (every named CHECK, every trigger, index and seed, every term of the five new triggers, both bounds of each range), the service (every WHERE term, every replay field, every closing-step and result branch), the routes, the policy service, the words and the contract, and the CLI. Gaps they found got tests (budget exactly spent, a pool whose available is negative takes everything but a hold, only a hold is closed, a partner pool named
peopleis not the budget, a job's charge is the job's own and not its pool's, a replay of another kind, a pool-side charge overflow, the default grant reason, escaped-quote spellings in the source scan).Round 2: 7 single-line mutations of the
placeHoldreplay branch (closed check dropped, release and settle words each forced, swapped, an open hold refused, only a release or only a settlement refused) and 1 of its order (the closed check ahead of the conflict check) were each caught; 11 of the narrowed trigger (each of hold, overrun and the final-settlement adjust dropped from the required kinds, the adjust term widened to a nonzero delta, a refund or a pool-level correction required again, every adjust required, the account-or-partner condition dropped) and ofcompute_ledger_budget_is_people(never firing for a refund or a correction, never firing for a hold) were each caught; a mutation of the refund statement to name no budget is caught, so option B in the code is pinned.Survivors, all equivalent mutants and not gaps:
compute_ledger_applyadding a granted delta to the budget (no entry that names a budget has one); the held terms ofcompute_ledger_totals_in_range(the hold-fits and closes-its-hold triggers refuse every row they could catch);compute_ledger_budget_requiredfor a release or a charge (the closes-its-hold trigger refuses a mismatched budget first); theNOT EXISTS (key)term ofFINAL_INSERT_SQLandREFUND_INSERT_SQLand theNOT EXISTS (hold open)terms of the release and settle statements (the unique index answers identically, and the service reads the unique violation as the same refusal); the route's owner check onPUT /compute/policyalone (the statement checks the role too; removing both is caught); the route's platform-key membership test (the lookup refuses an unknown key anyway; it narrows the type).Deviations and things to decide
job_already_heldis NOT added to the refusal codes, because with the hold's key derived from the job a second hold of the same job is a replay or anidempotency_conflictand the refusal cannot occur (the one-hold-per-job index stays as the backstop);COMPUTE_REQUEST_MILLI_MAXis 2^40 milli-SU and thewould_exceed_limitguard stays as well; a frozen BUDGET pool does not refuse a hold (documented: freezing applies to the holder's own pool); a deleted account is still read and its grant corrected, for the record.compute_ledger_closing_holdandcompute_ledger_budget_distinctare removed rather than kept as unreachable CHECKs (a trigger answers first for each, since SQLite runs BEFORE triggers ahead of CHECKs);compute_ledger.pool_idstill has no CHECK for the same reason.placeHold,releaseHold,settleProvisional,settleFinalandrefundJobchange shape: a hold takes noidempotencyKey, results carryreplayed,hold_closedcarriesclosedBy,refundJobhas noalready_refunded(a repeat is a replay), andsettleFinalalways returns its entry.peoplebudget with the pool; the interim rule only makes an account's charge correction the owner's. That question stays the repository owner's.mutate.py(it crashed on its first spec and mutated nothing), and I stopped it withpkill -f mutate.py, which may also have terminated another agent's mutation run if one was in flight; the other worktree should be checked for a leftover mutation withgit diff.defaultGrantMilli, freezing the budget pool in the hold, thefrozenwriter and tombstone freeze (A8), job-row batching and job-count guards (A3), settlement refund semantics (A5), the design page (section 5) and the runbook list (docs repository).