Skip to content

3.x.x: Bound the public artifact route: dedicated rebuild limit, in-flight cap, no post-permit hashing (#469) - #472

Merged
kiwidream merged 10 commits into
3.x.xfrom
p2-hardening/artifact-route-admission
Sep 22, 2026
Merged

kiwidream merged 10 commits into
3.x.xfrom
p2-hardening/artifact-route-admission

Conversation

@kiwidream

@kiwidream kiwidream commented Sep 18, 2026 •

Copy link
Copy Markdown
Member

Part of #469 (deferred half of #267). Base 3.x.x at d78659de. Admission only; sealing at landing is a storage decision recorded in #469 and not taken here.

What

  • /public/v1/artifacts/<sha> took no permit at all: a native block's canonical bytes (~1,112 B per share; 111 MB at 100k, 223 MB at 200k) were rebuilt from the window or digested and parsed inline on a runtime worker thread. Now a dedicated PRISM_PUBLIC_AUDIT_REBUILD_CONCURRENCY permit (default 1, 1..64), sized independently of read_concurrency, moves into the blocking job for both the sealed digest+parse and the unsealed rebuild (ledger::audit_canonical_bytes_admitted); a dropped request cannot free it before the job ends; waiting spends the request's own deadline.
  • PRISM_PUBLIC_AUDIT_ARTIFACT_MAX_IN_FLIGHT (default 32, 1..4096), taken with try_acquire on the audit branch only, after the two indexed point reads and before any audit read: beyond it 503 audit_artifact_busy with Retry-After: 5, never cached, counted in qbit_prism_public_audit_artifact_refusals_total (public-api role). CTV manifests on the same route are never throttled.
  • An audit artifact is no longer hashed twice on runtime threads after the permit is released: the bytes were digested against audit_bundle_sha256 inside the job, and the ETag is the content address. Response bytes and ETag values are identical.
  • Docs: sizing bound scoped to this route (/public/v1/blocks/<hash>/settlement-artifacts still rebuilds under audit_decodes sized by read_concurrency, documented as a follow-up), settings, ledger-ops paragraph, public API contract.

Evidence

  • 3.x.x: Normalize stored audit bodies so they stop growing with the window #267: "Artifact route at 50 req/s does not push pool-summary past its read deadline": tests/artifact_admission.rs:635 and the #[ignore]d large-window variant. Measured on the build host (PostgreSQL 16.15, defaults; debug build; 600 requests over 17 distinct hashes, 1 unsealed): 100k shares, three runs — pool-summary p50 0.066–0.067 s, p99 0.075–0.379 s, max 0.118 / 0.364 / 0.430 s, 0 non-200; 200k — max 0.139 s, 0 non-200. Before the double-hash fix one 100k sample hit 20.1 s (runtime starvation, not the pool).
  • Permit discipline incl. the unsealed path and cancellation; over-cap refusal with the two point reads and zero audit executions; refusal never cached nor shared with followers; isolation from read_concurrency (fails if the permit is taken from audit_decodes); byte identity for sealed and unsealed rows.
  • fmt, clippy -D warnings, the three Python checks, generate_prism_metrics --check; artifact_admission 25, api_database, api_2x, api_contract, share_archive 32, observability 17; landing, the settlement transaction, ledger/blocks.rs and ledger/archive.rs untouched.

Not covered

#267's "second artifact request for a 400k-share block performs no range scan" (needs sealing at landing); no 400k run (100k and 200k measured, 400k derived ≈ 445 MB); the settlement-artifacts route; operator-listener refusals uncounted; the Compose pass-through not executed (no docker on the build host); a scheduling-delay probe is printed, not asserted.

Merge after #467's and #468's PRs.

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

kiwidream and others added 10 commits September 22, 2026 15:26
An artifact read of a native block is window-sized work that outlives its
read connection: an unsealed block is rebuilt from its share range, a sealed
one has its stored canonical bytes digested and parsed. The route took no
permit at all, so N concurrent reads took N read connections and N windows of
memory, and the sealed path ran its digest and parse inline on a runtime
worker thread.

Both now run under a dedicated limit, PRISM_PUBLIC_AUDIT_REBUILD_CONCURRENCY
(default 1), built beside the imported-audit decode limit and resized with
it, but sized on its own: a larger PRISM_POSTGRES_READ_CONCURRENCY serves more
dashboard reads and admits no more windows. The permit moves into the blocking
job, as the bundle route's already does, so a dropped request cannot free it
before that job ends, and waiting for it spends the request's own deadline.

audit_canonical_bytes keeps its signature and delegates to
audit_canonical_bytes_admitted, which takes the permit; ledger-internal
callers keep passing nothing. Its rebuild now returns the canonical bytes the
materialization's own blocking job already produced and proved against the
row's digest, instead of re-serializing the rebuilt body on a runtime thread
afterwards, which is what lets one permit span the whole reconstruction.

Ahead of that, PRISM_PUBLIC_AUDIT_ARTIFACT_MAX_IN_FLIGHT (default 32) caps the
audit artifact requests running or queued. Past the cap a request is refused
after the route's two indexed point lookups and before any audit read, with
503 audit_artifact_busy, Retry-After and no-store, in microseconds rather than
a spent deadline. CTV manifests on the same route are served from stored JSON
and are never counted or refused, identical requests still collapse into one
computation, and a refusal is never cached. The public service counts them in
qbit_prism_public_audit_artifact_refusals_total, with HELP and TYPE.

Tests: tests/artifact_admission.rs drives the route at 50 req/s while
sampling pool-summary, and covers permit discipline under cancellation and
failure, the refusal's zero audit reads through the execution proxy,
isolation from the read concurrency, byte identity of both artifact shapes,
and the settings' validated ranges.

Co-Authored-By: Claude Opus 5 <[email protected]>
PRISM_PUBLIC_AUDIT_REBUILD_CONCURRENCY and
PRISM_PUBLIC_AUDIT_ARTIFACT_MAX_IN_FLIGHT reach a Compose deployment only if
Compose passes them, so both services forward them with the code defaults,
and the mainnet contract fixture pins non-default values through that path.

prism-storage-sizing.md gains the memory bound the route now has: rebuild
concurrency times the peak bytes per read, with the per-share canonical length
measured at 1,114 B and the peak-to-artifact multiples measured at a
5,000-share window, and the 400,000-share figures marked as derived from them
rather than measured. It also records that raising the read concurrency no
longer admits more window-sized rebuilds. prism-ledger-ops.md describes the
503/Retry-After refusal and both settings for operators.

Co-Authored-By: Claude Opus 5 <[email protected]>
The public role gains one family, so the inventory's family count moves from
14 to 15 and the note on untyped public exposition records its one exception.

Co-Authored-By: Claude Opus 5 <[email protected]>
The in-flight cap counts computations, and only the response cache makes two
identical artifact requests one computation; with it off each request is its
own. Say so where the cap is described.

Co-Authored-By: Claude Opus 5 <[email protected]>
…mers

The public contract already states the read deadline's 503 read_timeout and
the no-store rule; the artifact route's admission refusal is the second 503 a
client can see there, and the only response in this API that carries
Retry-After.

Co-Authored-By: Claude Opus 5 <[email protected]>
…cheability

Two paths the first round left unguarded. The cancellation test sealed its row
before gating the blocking thread, so only the sealed decode's permit was
proven to outlive its request; the unsealed rebuild holds its permit one level
down, inside the materialization, and a permit kept by the request frame
instead would have passed. The gate-and-time-out sequence is now a helper and
runs on both shapes, unsealed first.

The refusal was only ever exercised with the response cache off and with a
distinct-hash load that never reached the cap, so nothing noticed if a refusal
were stored as a cache entry or handed to a follower as a success. The new test
runs with the cache on and one admission slot held: every request that shares
the refused computation gets the same 503 and no-store, a later request is
still refused by the cap rather than from a stored body, and the first read
after the slot frees up computes the artifact instead of hitting the cache --
with a second read proving that success is cacheable, so that assertion is a
real one.

Verified by mutation: passing None into the materialization while the request
frame holds the permit, storing an Entry for a refusal, and returning the
refusal as Ok(payload) each make exactly these tests fail.

Co-Authored-By: Claude Opus 5 <[email protected]>
Three corrections to what the admission half claims.

The sizing and operations notes said a larger read pool admits no more
window-sized reads. That is true of /public/v1/artifacts, not of the public
service: /public/v1/blocks/<hash>/settlement-artifacts falls back to the
audit-bundle reader for a block with no CTV fanout set, and that reader still
rebuilds or decodes the window under the shared imported-audit decode limit,
which is sized from PRISM_POSTGRES_READ_CONCURRENCY. Both bounds are now stated,
with the note that moving that route under the artifact limit would change
another route's behaviour and is a follow-up.

The bound also covers only what the permit admits. The route's own re-hash of
the returned bytes, the ETag digest and the response body all outlive the
permit, so a read's footprint exceeds it by about one more copy of the
artifact; the two SHA-256 passes are pre-existing and unchanged here.

The refusal counter is a public-service metric: the mining process serves the
same route on its operator listener and applies the same cap, but has no
public-service metrics owner, so those refusals are uncounted. The inventory
meaning says so.

Co-Authored-By: Claude Opus 5 <[email protected]>
At a 100,000-share window the route's own 50 req/s criterion failed: 1 of 84
pool-summary samples took 20.137 s and came back as a failed node RPC, while
the read pool was idle (p99 0.107 s). The cause was not the pool. Every 200
response hashed the whole 111 MB body twice more after its permit was released
-- once to check the returned bytes against the requested address, once for the
ETag -- and one SHA-256 pass over that body measures 1.6-1.8 s in a debug
build, so 73 responses of CPU-bound work saturated the four worker threads. The
load harness now measures both halves of that: one pass over the artifact, and
the overshoot of a task that only sleeps, which reached 23.534 s against a
median of 0.001 s.

Neither pass was buying a guarantee the request did not already have. The bytes
are digested against `audit_bundle_sha256` inside the blocking job, under the
permit, and the row is the one that column matched, so comparing the row's
digest to the requested address as a string proves the same thing; the ETag is
that address, which is the hash of these bytes by construction, so a payload
served by its content address now carries it instead of being hashed again. The
manifest branch still hashes its own small body and serves it under the address
that proved it. No digest verification is weakened and responses, ETag included,
are byte-identical.

The same load now leaves pool-summary at 0.118 s maximum with no failed sample
and the sleeping probe's overshoot at 0.435 s, and the load window drains in
28.9 s instead of 57.3 s.

Co-Authored-By: Claude Opus 5 <[email protected]>
The sizing note listed the route's re-hash and its ETag digest as work outside
the memory bound. Both are gone, and the reason belongs in the same section:
one SHA-256 pass over a 111 MB artifact measures 1.6-1.8 s in a debug build, so
at 50 requests per second those passes saturated the public process's worker
threads and failed pool-summary on a node RPC while the read pool was idle. The
section now states what the bound covers, what the removal changed, the before
and after numbers, and that the legacy fallback body is still hashed for its
ETag because it has no proven content address to carry.

Co-Authored-By: Claude Opus 5 <[email protected]>
@kiwidream
kiwidream force-pushed the p2-hardening/artifact-route-admission branch from 5deb435 to 75aee88 Compare September 22, 2026 19:37
@kiwidream
kiwidream merged commit 629cbfb into 3.x.x Sep 22, 2026
21 checks passed
kiwidream added a commit that referenced this pull request Sep 22, 2026
djh58 added a commit that referenced this pull request Sep 22, 2026
Refs #493. Resolves the scenario fixture as a by-name union (the #463
advisory-lock scenarios plus this branch's landing cases) and regenerates
the deployment patch. The native paging-rule assertion now also covers
the #463 advisory-lock critical, which already satisfies it; the exact
set check becomes a subset check so new paging rules are covered rather
than listed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
kiwidream added a commit that referenced this pull request Sep 24, 2026
…native tests (#460) (#465)

* test(prism): pin every window-multiplier literal to the constant

The payout window's difficulty multiplier has one value,
qbit_prism::PRISM_WINDOW_MULTIPLIER, but several spellings: the dashboard
query files and the shipped schema bake it in as a SQL literal, the archive
horizon spells it in inline SQL, and two read models render it into JSON.
Nothing tied those copies together, so raising the multiplier could leave a
dashboard or the audit window view scaling by the old value.

The new test enumerates the literals across the server's Rust and SQL
sources and the shipped schema, asserts each equals the constant — listing
every disagreeing site in one failure rather than stopping at the first —
and asserts the discovered site set is exactly the expected one, so a new
spelling, or a site the scanner stops recognising, fails with a message
telling the author to derive it from the constant or extend the list. A
scanner that matches nothing fails too. The frozen 2.x schema fixture and
the rollback scripts are outside the scanned roots.

Closes one needs-triage row of docs/prism-deleted-test-map.md (#460).

Co-Authored-By: Claude Opus 5 <[email protected]>

* test(prism): assert the divergent landing's alert and its provenance

Landing an offered block whose as-issued prior balances are no longer the
canonical ones is allowed — the node has or may have the block — but it is
reported. The refusal, the marker and the additive balances were covered;
the warning itself was not, so it could have been dropped silently.

The new test moves the canonical balances the way production moves them:
a second block of the same window lands, is confirmed, and its carry rows
accrue a below-floor account, so `SUM(gross - onchain)` shifts. Landing the
held claim on those moved balances must raise exactly one WARN naming the
block, its lifecycle state and both digests, and the same test holds the
landing to the rest of its contract — the provenance marker records the
audit that was issued, the carry rows keep the as-issued priors rather than
the moved ones, and the integrity validator stays clean — so the test
cannot pass on the warning alone. A control with no mover asserts the
marker is written anyway and no alert is raised. The subscriber is attached
to the landing future alone, never installed globally, because this binary
runs many tests.

Closes one needs-triage row of docs/prism-deleted-test-map.md (#460).

Co-Authored-By: Claude Opus 5 <[email protected]>

* test: qualify the audit reconstruction permit contract

`materialize_audit_row` hands its permit to the blocking job rather than
holding it in the caller's future, because Tokio keeps running a queued
job after the future that awaited it is dropped. Nothing proved that.

Three gated tests drive the function directly, each on a runtime with a
single blocking thread the test parks, so ordering is a fact and no
assertion reads a clock:

- a caller dropped after its job is queued does not release the permit;
  it comes back only once the released thread has run the job;
- a second caller waiting on the same one-permit semaphore reaches no
  statement of its own until that job ends, and both rows then hydrate
  to the signed body and its declared canonical digest;
- EP-ERRORS: a digest mismatch inside the job returns the permit when
  the job ends and not before, while a missing snapshot row and a
  cancellation on the first statement return it with the future.

Row 216 of the deleted-test map moves from `needs triage` to `partial`:
the permit bound is the property now covered, and the bounded audit-body
read the retired Python streaming view asserted is not, since
`materialize_audit_row` still hydrates the whole share array.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(prism): reconcile the deleted-test map for the three closed rows

Integration edits on top of the #460 R1, R2 and R3 tests: the multiplier
scanner also walks crates/qbit-prism-server/migrations/, so a migration that
redefines the window view cannot add a copy unnoticed; row 216 states what the
permit tests do not observe (the job holding its permit for its whole
duration); the summary counts and the "Needs triage" section follow the rows
that left it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Bind Stratum listeners before coordinator startup

Move the primary Stratum bind, its "PRISM listening" line and the high
difficulty bind above Coordinator::new. Coordinator startup registers the
instance with a `starting` row and nothing retracts it when run returns an
error, so a restart that lost the bind race to its predecessor left a row
behind that `fatal-state clear` refuses on. Every fallible step before
Coordinator::new now touches only configuration and sockets.

The log line's instance and worker fields come from the Config before it
moves into the coordinator; their values are unchanged. The audit HTTP
listener still binds after Coordinator::new because it serves the
coordinator's ledger through ApiState.

Co-Authored-By: Claude Opus 5 <[email protected]>

* test: qualify the Stratum bind order on restart

Add a gated target that runs the real server binary against a fake node and
a database of its own, and proves what the bind order buys. A restart whose
primary or high difficulty port is still held by its predecessor exits with
the bind error and code 1, and qbit_prism_instances stays empty, so nothing
is left for `fatal-state clear` to refuse; the next start on a free port
serves and stops cleanly. While the node holds the chain check inside
Coordinator::new, the announced primary address already accepts a
connection and the instance is still unregistered. The high difficulty
listener is bound when, and only when, its port is configured.

Not covered, and named in the map row: bind retry against a draining
predecessor, retry abort on shutdown and zero-retry fail-fast, which native
`run` has no subject for, and port release on a shutdown during the node
readiness wait, which needs a signal handler that does not exist yet.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(prism): reconcile the four #460 rows onto the reconciled map and drop the duplicated partition attach

* docs(prism): cite #472's artifact admission tests on the audit-view row instead of the closed #267

* ci: re-run after an unrelated latency-bound qualification flake (incident_2_ack_latency)

---------

Co-authored-by: Claude Opus 5 <[email protected]>
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