Anvil concurrency and approval: source findings and bounded measurements¶
Observed 2026-11-09 America/Los_Angeles. Research only; no policy change or production State mutation. Source: an isolated Kanban worktree, base 362c3446edc7ab80919718624bfd95d996634fc6 plus the uncommitted Kanban changes. The benchmark JSON records hashes of the relevant source files, Python 3.11.16, and SQLite 3.53.1.
Main finding¶
The current design can have many active leases, but it deliberately serializes State mutations. More HTTP threads or worker containers do not increase the write critical section's capacity. Full canonical snapshots also acquire that exclusive lock; a board refresh measurably blocks writers. The new action projection is a small fraction of the refresh cost. Proof intake and Git event mode have additional costs absent from the lightweight readiness benchmark. There is no demonstrated thousand-container capacity.
Measured reader/writer contention¶
Artifacts: /tmp/anvil_snapshot_contention.py and /tmp/anvil-snapshot-contention.json. Temporary synthetic State only. Fixture: 1,000 ready tasks, 1,008 events, 602,725 event-log bytes, local event mode. Three unprofiled repetitions; a separate cProfile pass identifies cost centers and is excluded from latency measurements.
| Stage | Observed time, milliseconds |
|---|---|
| Canonical snapshot before new board projection | 1,344–1,410 |
| Event frontier validation | 279–281 |
| Hierarchy payload construction | 244–247 |
| Explicit payload digest | 226–262 |
| Explicit serialized-size enforcement | 46–48 |
| Typed task reread | 17–37 |
| All task action availability | 13.5–13.8 |
| All actionable task versions | 15.3–15.6 |
| Complete board projection | 1,403–1,465 |
Snapshot substages do not sum to total: Pydantic response construction repeats hierarchy, raw-limit, serialized-limit and digest validation. The profile recorded roughly 17 million Python calls; recursive canonical JSON construction and repeated DTO validation dominate. This is evidence for investigating redundant validation and immutable capture boundaries, not permission to bypass those checks.
Each contention arm used eight pre-initialized backend connections and 100 independent ready→drafted transitions. The reader arm intentionally began writers after one full-board reader had acquired the State lock, showing the cost of an actual collision rather than estimating steady-state traffic.
| Workload, three repetitions | Writer p95 | Writer max | Throughput |
|---|---|---|---|
| Eight writers, no reader | 14.2–17.5 ms | 150–334 ms | 295–645 moves/s |
| Eight writers overlapping one board read | 1,621–1,637 ms | 1,712–2,087 ms | 47.8–57.8 moves/s |
All six arms verified exactly 100 changed tasks and 100 matching transition events: 600 transitions total. No errors or lost transitions occurred in this bounded run. These are threads with separate connections, not independent processes or containers. They exclude claims, renewal, proof validation, worktree creation, approval, HTTP and DOM rendering. The prior baseline additionally measured fresh CLI startup at about 0.65 seconds per lightweight move; persistent native clients avoid that startup while retaining engine controls.
Lock and cost map¶
All paths below are relative to the source checkout; symbol names are more stable than line numbers while the shared worktree is being edited.
- Single event-log writer.
bin/src/anvil/state/sqlite.py:1176,SqliteBackend._append, holds_append_lockacross payload validation, action-specific guards, event identity, JSONL append, optional fsync, SQLiteBEGIN IMMEDIATE, projection and commit._append_lockat 5295 combines a per-backend process lock and an exclusive cross-process event-file flock. Retry is exponential with jitter, approximately 10–500 ms steps and a five-second deadline. This is bounded waiting, not FIFO fairness. Slow proof or Git validation extends the same critical section for all tasks in that State. - Canonical reads also exclude writers.
sqlite.py:730,query_only_transaction, takes the same exclusive event flock before SQLite BEGIN and holds it until the consumer finishes. It also holds a process-global initialization lock.project_snapshot.py:362,_event_cursor, scans the whole log into temporary SQLite, checks event/projection agreement and hashes the frontier.snapshot_from_transactionthen builds and validates the hierarchy. The whole operation is inside the event lock; WAL does not make this path concurrent with append. Action availability and selected versions share the transaction for correct binding, adding about 55–73 ms on this fixture. - Claims may hold the lock across Git I/O.
sqlite.py:5356,claim_operation_lock, spans reads, append and caller-owned Git mutation/compensation.cli/claim.py:612demonstrates revalidation and worktree/branch application inside that lock. Root-set operations acquire the owner registry before State:roots/registry.py:804,ordinary_claim_coordinator, androot_set_use_authorized. When the registry is activated, its owner-wide lock can serialize otherwise distinct project claims; preserve global→State lock order. - Scheduling scans the project.
claims/manager.py:308,diagnose_next_offer, loads all tasks and active claims, computes done dependencies and active conflict groups, filters candidates and sorts eligible tasks. Cost grows with tasks, dependency edges, active claims and ready candidates; per-worker polling repeats it.next_ready_excluding_active_filesadds another task/claim pass when files are held. A central bounded dispatcher or cached offer index is a hypothesis; the final claim guard must remain authoritative. - Renewal is actual progress, not a free heartbeat.
claims/manager.py:1213,renew_with_result, requires current owner/lease, maximum age, and fresh claim-bound progress attestation or file progress._has_progress_sincequeries recent file events per expected file. Defaults are a four-hour lease, five-minute heartbeat and maximum age four times the lease; these are implementation defaults, not a scale recommendation.claims/stale.py:39scans all active ordinary and bundle claims, then emits a separate event for each expired public claim. Repeated invocations and synchronized expiry bursts need qualification. - Proof intake has bounded but material CPU/I/O.
sqlite.py:12829,_claim_command_proof_material_is_valid, decodes proof bytes, checks canonical/output hashes and successful exit, and verifies trusted signatures when required._claim_command_proof_batch_matches_claimat 13110 and_hook_command_proof_batch_matches_claimenforce exact task, actor, claim generation, captured time and durable attribution._check_evidence_submittedat 13315 invokes these under the append lock. Limits instate/models.py:664are 16 KiB command, 128 KiB output, 256 KiB individual artifact, 16 proof items and 1 MiB aggregate proof batch. These bound one request, not cumulative ledger growth or verification throughput. Legacy evidence shapes and configured contracts differ; plain command strings are not equivalent to independently trusted execution receipts. - Git event mode adds history-dependent work.
sqlite.py:5657,_git_path_signature, hashes all event-log bytes even when stat metadata is unchanged, defending same-length/mtime-restored rewrites._validate_git_log_before_appendat 5690 invokes this before every append; changed bytes trigger full ordering/material/projection/head checks. Append computes a signature again afterward. With multiple backend instances, each sees other instances' changes. Local-event readiness throughput therefore cannot be extrapolated to Git event mode or a large historical log. - Log-first durability affects retries.
_appendlogs before DB projection. Strict durability fsyncs the log and uses stronger SQLite synchronization; default normal mode has different crash guarantees. A post-log DB failure deliberately leaves the durable event and raisesTransactionAborted; initialization catches projection up. Distinguish pre-log refusal/lock timeout from uncertain or post-log success. A persistent client needs durable operation receipts and reconciliation, not blind replay with a new identity.
The official SQLite documentation describes one WAL writer with concurrent SQLite readers, and the shared-memory same-host constraint. Anvil's extra event-log lock is stricter than SQLite's ordinary reader concurrency. Never share this WAL database over a network filesystem as a shortcut to fleet coordination. Sources: SQLite WAL, SQLite isolation.
What approval currently blocks¶
- Exact approved PRD/source bindings authorize claiming within scope. Existing user authority permits routine work/claim/submit; it does not require a new conversational pause for every progress event.
- Completion submission checks attribution, stores evidence, releases the member claim and moves the task to
needs_review. Ordinary dependency readiness requiresdone, so pending acceptance blocks true downstream dependencies, while unrelated ready tasks can continue. anvil apply --approverequires explicit disposition authority under AGENTS.md. Successful apply records acceptance thendone. Current task approval is per member; the new browser has bound previews, and the new native task-action path does not approve anything.- Three independent adversarial reviews remain required by project instructions. Bundle review enforces distinct reviewers and angles; reviewer identity strings are not cryptographic proof of separate humans/agents. Final human project validation and protected root/delivery gates remain separate.
- Evidence enforcement is not universally strict today:
packet_apply.py:1696resolves strict-evidence flag/config, and no required-evidence fields can make that check a no-op. Contract evaluation is auto-strict when it produces an enforceable failed verdict, but_claim_verdict_blockat 360 catches evaluator exceptions, warns and returns no verdict._merge_check_blockat 288 likewise skips a failed probe, including configured strict mode. A future automated acceptance policy must define required-verifier errors as unknown/refused; it cannot safely infer proof rigidity from--strictalone. The Kanban implementation now refuses required-verifier errors for strict or preview-bound approval, with regression coverage. Legacy non-strict informational behavior is preserved; a future autonomous policy still needs explicit verifier availability and receipt rules.
Existing bulk mechanisms and their limits¶
sqlite.py:5373,collect_planning_batch, simulates planning under a rollback savepoint, then commits one outer event. It keeps the event lock for collection and commit.state/payloads.py:547caps this at 10,000 operations / 16 MiB. This is bounded planning, not bulk proof intake.- Task review can operate over an explicit PRD or all PRDs; this prepares ready work but does not accept completed implementation evidence.
- Bundles provide one coordinator with member authorizations, file/group conflict checking and an aggregate review/delivery lifecycle.
bundles/manager.py:195checks ready members, graph and external done dependencies; internal dependencies are handled within the bundle.BundleThroughputBudgetinstate/models.py:1717defaults to 12 tasks / six serial stages, hard cap 500. The 500 cap is a SQL-bound escape hatch, not measured capacity. - A single
bundle.claim_renewedevent updates the public coordinator lease and all active member leases (sqlite.py:10551). Aggregate readiness still verifies each member's status and evidence, and three independent reviewers/angles are the non-configurable review floor. bundle finalize-reviewdoes not apply member acceptance or merge branches.docs/how-to/coordinating-a-bundle.md:77explicitly requires separate member apply under established authority. Release/expiry can require replacement/replan; it is not harmless pause/resume. Bundles reduce coordination handoffs, not the proof obligations or the acceptance event count.
Recommended sequence of design experiments — hypotheses only¶
- First reduce redundant dashboard reads. Coalesce simultaneous reads per State into one in-flight refresh, then fan out the identical validated result. Consider a short-lived explicit last-validated snapshot cache with its frontier and observation age; never relabel cached data as current. A selected mutation must still obtain fresh current state and pass engine CAS. Expire/invalidate after known local changes, retain a bounded TTL for external writers, and use a minimum refresh interval rather than letting each tab trigger independent full scans. This can reduce frequency, but does not shorten one lock hold.
- Explore immutable capture, not weaker validation. Capture a complete bounded DB view plus exact matching log bytes/frontier while locked, then perform expensive canonical serialization and repeated shape/hash validation on that immutable material outside the lock. This requires an explicit capture contract and tests against same-size log rewrite, event/DB mismatch, mutable proof paths and resource exhaustion. Releasing the lock while reading live log bytes is not equivalent. Measure before adopting; avoid casually trusting stat metadata.
- Separate execution admission, proof verification and human exception queues. A persistent native client/coordinator can amortize CLI startup. Bounded queues should report admission, durable receipt, verification pending, refused and accepted separately, with backpressure and retries tied to operation identity. Do not return accepted before durable append; do not invent an unjournaled offline mutation path.
- Move expensive verification only with exact rebinding. A verifier could validate immutable, content-addressed evidence outside the writer lock and issue a receipt bound to task/claim generation, source/contract digest, policy/verifier version, artifact bytes and expiry. The short append still checks lease/custody, current task/version, policy revocation and receipt identity. Mutable filesystem assertions need artifact/tree binding; a cached successful verifier result alone cannot authorize a later changed file.
- Introduce explicit scope-policy authority only after user adoption. Approve a bounded manifest of task IDs/generations, source and dependency scope, allowed operations/risks, verification contract, independent review requirements, artifact rules, resource/time ceilings, revocation and exceptions. Ordinary execution within this authority can proceed without per-task conversation. Material scope/policy changes need a new authority event. This is richer than a blanket approve-all button.
- Keep individual proof and aggregate acceptance distinct. Record per-task machine verification as its own fact, then aggregate
all_proven,partial,failedandunknownfrom exact members and receipt digests. A human may accept the bound aggregate only with explicit policy for its dispositions; one passing sample never approves unproven members. If machine proof is to release dependencies before human delivery acceptance, model and approve that dependency semantic explicitly rather than silently redefiningdone. - Partition or add a supported backend only after measured need. Independent project States can distribute ordinary contention, but cross-project dependencies/root reservations need coordinated policy. A new backend must preserve append/replay, custody and refusal behavior. SQLite's one-writer property is not itself proof that a server database is required; arrival rate and lock duration matter more than the number of sleeping containers.
Next bounded qualification envelope¶
Proposed, not executed by this study:
- Pin source, schema, event mode, SQLite/Python, storage and durability. Use isolated temporary States; preserve real serving and canonical State.
- Distinguish 1,000 resident tasks, 1,000 active leases, 1,000 executing containers and 1,000 simultaneous append callers. They are separate quantities. For example, 1,000 leases at a five-minute renewal interval average 3.33 renewals/s, but synchronized renewals produce a 1,000-request burst.
- Start with 1,000 tasks, process writers 1/8/32, current log and 10k/100k historical events, local normal/strict durability; separately qualify Git event mode. Measure claim/renew/progress/submit/review paths and proof batches of 1/16 items at realistic and maximum bytes. Limit cell duration and storage before running; do not launch 1,000 containers to test database-only behavior.
- Run no-reader, one coalesced reader and repeated-reader arms. Capture per-stage lock wait/hold, DB commit, hash/signature/profile/artifact time, process startup, throughput, p50/p95/p99/max, timeout/retry counts, fairness and lease expiry. Report offered load and queue depth, not just completions/sec.
- Exercise same-task claim races, generation renewal/reclaim, stale source/evidence, duplicate receipts, verifier errors, revoked authority, owner stop, log-written/DB-not-committed crash and restart replay. Verify exact successful event counts, no false
done, no double custody, every refused outcome, no lost accepted receipt, converged snapshot and deterministic replay. - Only after machine-level cells pass, run a small actual-container wave (for example 8 then 32) through worktree/runner/capture/submit, with required proof and independent review. Expand to 128/1,000 only when the prior level meets an explicit latency/error/lease-margin budget and resource stop conditions. Those budgets require workload choice; the current synthetic measurements do not define them.
This sequence targets the user goal of bulk execution with rigid proof, while preserving current human authority until a concrete revised policy is explicitly adopted.