Skip to content

Phase A2: Allocation ledger and owner policy - #2032

Merged
neuromechanist merged 25 commits into
feature/issue-2005-epic-compute-corefrom
feature/issue-2007-phase2-allocation-ledger-and-owner-policy
Nov 4, 2026
Merged

neuromechanist merged 25 commits into
feature/issue-2005-epic-compute-corefrom
feature/issue-2007-phase2-allocation-ledger-and-owner-policy

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Migration 0114_compute_ledger.sql: compute_policy (one immutable row per version), compute_pools (per holder and pool, with the four platform pools seeded) and compute_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.
  • The ledger is the only writer of a pool's totals: the AFTER INSERT trigger compute_ledger_apply adds 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, holdStatements and placeHold (one conditional INSERT, meta.changes as the winner test, caller guards through extraGuards), releaseHold, settleProvisional (a charge and any overrun in 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) and backend/src/routes/admin/compute.ts (policy and pool routes, { error, code } refusals, an Idempotency-Key on every write, an audit row per write).
  • shared/contract/compute-admin.ts (error words, request cap, open response schemas only) and nemar admin compute policy show|set and pool show|grant|adjust.
  • ADR 0118 amendment of 2026-11-04 and section 7 of .context/compute-program/implementation-notes.md.

Round-1 fixes (Opus checkpoint and the review panel)

  • Refund then final cannot re-charge: settleFinal after a refund is refunded (a NOT EXISTS term in FINAL_INSERT_SQL).
  • A job's final settlement happens once even when it equals the charge: migration 0114 allows a zero-delta adjust only when it carries a job, forbids a granted delta on a job-scoped adjust, and FINAL_INSERT_SQL no longer skips a zero difference, so the key job:<id>:final always records it.
  • The budget rules the table enforces (narrowed in round 2, below): a budget an entry names is the platform people pool 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).
  • The table refuses what the WHERE refuses, under INSERT OR IGNORE, OR FAIL, OR REPLACE and 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 (REPLACE skips the append-only DELETE trigger on D1; DROP TABLE removes the triggers and a rebuild must copy rows before creating compute_ledger_apply).
  • The source scan refuses any INSERT OR <x> into the ledger, any UPDATE [OR x] of the pools that names a total in any quoting, schema or escaped-quote spelling, REPLACE and DELETE on either table, and any second trigger on compute_pools; 36 planted spellings must each fail it and the legitimate statements must pass.
  • Interim rule: an account's CHARGE is corrected by an owner only (an administrator corrects a grant); platform adjusts and the policy stay owner-only. The budget semantics of a charge correction and of a refund are the repository owner's decision (round 2 takes them out of the schema); the ADR and notes say what the code does today.
  • A refusal nothing explains is insufficient_balance unless the caller passed a guard (guard_refused); an adjustment naming a budget that is not there is pool_not_found.
  • An idempotency key is compared on every field (kind, pool, budget, amounts, job and reason) by one replayOrConflict; an administrator's key is stored as grant:<actor>:<key> and adjust:<actor>:<key>; a caller's key may not start with job: or hold:.
  • Closing steps are replayed (replayed: true with the closing entry) and hold_closed says whether a release or a settlement closed the hold (closedBy); a hold takes no key of its own, its key is holdKey(jobId) (job:<id>:hold).
  • Every exported *_SQL statement is checked with EXPLAIN QUERY PLAN (aliases resolved) for a scan of compute_ledger; FINAL_INSERT_SQL and JOB_CHARGE_SQL now use compute_ledger_closes_once and compute_ledger_job.
  • A deleted account is not granted to (404 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.
  • A total that would pass 2^53 - 1 is a 409 would_exceed_limit, and one request may move at most 2^40 milli-SU (both chosen: the cap is COMPUTE_REQUEST_MILLI_MAX, and the overflow guard stays for a long run of grants).
  • The grant route looks at the key before it makes the pool, so a key reused for another pool word leaves no empty pool.
  • Words once: guard_refused in the refusal codes with its status, COMPUTE_LEDGER_REASONS in shared/compute-state.ts, HoldRefusal derived by Extract, COMPUTE_PLATFORM_KEYS used by the route and the CLI, drift tests for the holder kinds and the platform keys, and ADR decision 10 names compute-admin.ts.
  • Dead code removed (computeErrorCode and its pin, MAX_MILLI, the holder-kind aliases, the route's MAX_SAFE, zodFields), issuesOf(error, prefix?) is the one copy, and a behaviour test checks every schema of compute-admin.ts accepts and keeps unknown keys at every depth.
  • PUT /compute/policy answers 403 owner_only for an administrator before the body is read (an invalid and a non-JSON body expose no field list), pinned by test.
  • Docs: the "BigInt" claim is gone from the service docblock, the ADR amendment says what the closing INSERT takes from the hold, what the budget triggers enforce and that retention and anonymisation of holder_ref and actor_user_id are 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

  • A hold replayed after it was closed is refused. placeHold of a job whose hold was released or settled returned { ok: true, replayed: true } while the pool's held was 0, so a caller could believe the job still held SU and a later settle was hold_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 an idempotency_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.
  • The schema no longer encodes the owner's open budget decision. compute_ledger_budget_required required every refund and every pool-level charge correction on an account or partner pool to name the people budget, 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 the people budget or none; compute_ledger_budget_is_people still 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.
  • Crediting the budget back on a refund or a correction is a code choice and says so in the migration header, the trigger comment, ADR 0118 amendment item 5, section 7 of the implementation notes and the docblocks: option A, the people budget 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)

  • Changed: compute_ledger_deltas (an adjust with a job carries charged only, which may be 0; an adjust without one is exactly one of granted or charged) and compute_ledger_budget_kinds (an adjustment that carries a job may name a budget).
  • Removed: compute_ledger_closing_hold (the closes-its-hold trigger answers first for every row it covered) and compute_ledger_budget_distinct (the budget trigger answers first); compute_ledger_budget_platform is replaced by compute_ledger_budget_is_people and compute_ledger_budget_required.
  • Added five BEFORE INSERT triggers: compute_ledger_totals_in_range, compute_ledger_hold_fits, compute_ledger_closes_its_hold, compute_ledger_budget_is_people and compute_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 head 94b1bc9f, which sat on the epic branch after A1b, 7ba7d2f1):

  • The issue's eight-file bun test command: 326 pass, 0 fail (8 files).
  • The new rules, EXPLAIN and trigger tests (backend/test/compute-ledger-rules.test.ts, the table-rule tests inside compute-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 check on every file this branch touches: no errors (7 noExplicitAny warnings in test files).
  • bunx biome check src shared backend/src: "Found 5 errors. Found 1 warning." The five errors are noUselessElse in backend/src/services/zenodo.ts and the warning is in backend/src/services/doi-orcid-discovery.ts; neither file is touched by this branch.
  • The full bun test is the driver's to run; the one failure it had before this round was test/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 people is 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 placeHold replay 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 of compute_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_apply adding a granted delta to the budget (no entry that names a budget has one); the held terms of compute_ledger_totals_in_range (the hold-fits and closes-its-hold triggers refuse every row they could catch); compute_ledger_budget_required for a release or a charge (the closes-its-hold trigger refuses a mismatched budget first); the NOT EXISTS (key) term of FINAL_INSERT_SQL and REFUND_INSERT_SQL and the NOT 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 on PUT /compute/policy alone (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

  • Decisions inside the brief that you may want to reverse: job_already_held is 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 an idempotency_conflict and the refusal cannot occur (the one-hold-per-job index stays as the backstop); COMPUTE_REQUEST_MILLI_MAX is 2^40 milli-SU and the would_exceed_limit guard 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_hold and compute_ledger_budget_distinct are removed rather than kept as unreachable CHECKs (a trigger answers first for each, since SQLite runs BEFORE triggers ahead of CHECKs); compute_ledger.pool_id still has no CHECK for the same reason.
  • placeHold, releaseHold, settleProvisional, settleFinal and refundJob change shape: a hold takes no idempotencyKey, results carry replayed, hold_closed carries closedBy, refundJob has no already_refunded (a repeat is a replay), and settleFinal always returns its entry.
  • The budget accounting of a charge correction and of a refund is untouched: both still move the people budget with the pool; the interim rule only makes an account's charge correction the owner's. That question stays the repository owner's.
  • Process note for the driver: my first mutation sweep of this round ran a runner that the shared scratchpad had overwritten with another phase's mutate.py (it crashed on its first spec and mutated nothing), and I stopped it with pkill -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 with git diff.
  • Not done, as instructed: a per-grant ceiling relative to defaultGrantMilli, freezing the budget pool in the hold, the frozen writer 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).

@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR2032

Version: 0.10.28-PR2032.ff50df0
Commit: ff50df0


🤖 Updated on each push.

@neuromechanist
neuromechanist force-pushed the feature/issue-2007-phase2-allocation-ledger-and-owner-policy branch from 5c7246b to 94b1bc9 Compare November 4, 2026 14:40
@neuromechanist

Copy link
Copy Markdown
Contributor Author

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 people budget back (option B, what the code does today with the interim owner-only rule on account charge corrections) or only moves the person's pool (option A, the budget records consumption). The schema no longer decides it: it is a code choice, and the decision is needed before phase A5, the first caller of refundJob.

@neuromechanist
neuromechanist merged commit 941ba78 into feature/issue-2005-epic-compute-core Nov 4, 2026
18 of 19 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-2007-phase2-allocation-ledger-and-owner-policy branch November 4, 2026 15:01

This branch was previously deployed

1 inactive deployment
npm — ff50df04 Deployed Nov 4, 2026 by neuromechanist via publish #4152
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant