Repository navigation
Serve content-addressed artifacts as their exact canonical bytes - #154
Conversation
GET /public/v1/artifacts/{sha256} re-serialized every artifact through the
generic write_json path (json.dumps sort_keys=True, default separators, plus
a trailing newline), while manifest and manifest-set hashes are computed over
canonical_json_text (compact separators). sha256(response body) therefore
never matched the advertised hash, so no external verifier could confirm any
artifact byte-for-byte.
The ledger already persists the exact hashed text (manifest_json /
manifest_set_json) next to the JSONB copies. Serve it:
- share_ledger: dashboard_public_artifact_canonical_json on both backends
returns the persisted canonical text for CTV manifests and manifest sets,
None for audit bundles (their Rust struct-order canonical bytes are not
stored).
- public_api.artifact: wrap the canonical text as RawJsonBody after
verifying sha256(bytes) == the requested hash; fall back to the legacy
re-serialized response on any mismatch so a store-integrity fault can
never serve bytes that contradict the content address.
- audit_http.write_json: write RawJsonBody bytes verbatim with
Content-Type: application/json; no re-serialization, no trailing newline.
No hash definition changes; historical hashes stay valid. Audit bundles keep
the legacy response until their canonical bytes are persisted at hash time;
the expectedFailure regression marker documents that remaining gap.
Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6f3bd7fd67
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 6f3bd7f. Configure here.
Review follow-up: the standalone canonical-json lookup duplicated the
legacy artifact query's predicates and added a second sequential read per
uncached request — and since the response cache stores only 2xx results,
arbitrary 404 probes against the unauthenticated endpoint paid both
statements (four unindexed table probes) every time.
Replace both reads with one dashboard_public_artifact_document() read
model returning {payload, canonical_json} from a single statement: the
audit/set/artifact lookups become shared CTEs selecting the JSONB copy and
its persisted canonical text together, so every request — hit, miss, or
audit bundle — touches each artifact table at most once, exactly like the
pre-change query. dashboard_public_artifact() delegates to it, and
public_api.artifact() consumes the document with the same sha256
self-verification and legacy fallback semantics.
Co-Authored-By: Claude Fable 5 <[email protected]>
|
Addressed the double-lookup finding in 375b2c2: the canonical text now rides the existing artifact query instead of a second statement. Deliberately not adding indexes on |
… tier Rebasing the read-tier extraction onto 2.x.x put it on top of #154, which landed while this PR was in review. Git merged the two textually, but the result was semantically broken in both directions: - audit_http kept #154's `public_api.RawJsonBody` branch in write_json while the extraction removed the public-API import, so every audit response raised NameError. GET /public/v1/artifacts/{sha256} moved out of this listener, so no route reaching it can carry pre-serialized bytes: the branch is dead here and is removed, restoring the module's import isolation. - public_read_service.write_json re-serialized every payload with sorted keys and a trailing newline. The artifacts route moved into this process, so #154's fix silently regressed: sha256(response body) would no longer match the advertised artifact hash. The RawJsonBody branch moves here with the route it serves. The two byte-exactness tests #154 added now exercise the extracted handler rather than the coordinator's audit handler, which is what pins the regression: they fail without the branch above.
* Extract the PRISM public read tier into its own process (#145) The coordinator served its public dashboard API on the same in-process listener as its operator endpoints, under the same GIL that acknowledges shares and lands blocks, against the same primary Postgres the lease-holding writer commits through. Read traffic scales with public interest rather than hashrate, so it was the one workload whose volume the pool does not control -- and it sat on the money path. Exactly the 13 /public/v1 routes classified Disposition.EXTRACT move. /healthz, /metrics, /audit/*, /owed* and the miner/payout status aliases stay on the coordinator, per docs/prism-public-operator-endpoint-split.md. Sever the two writer-lock reads on public routes first; without this the move would relocate GIL contention and keep lock contention: - PsqlShareLedger.dashboard_miner_owed_balance_bits filters one recipient in SQL through _run_read_json, replacing owed_balance_for_recipient's scan of every recipient's balance under the writer lock. That made /public/v1/miners/{recipient_id}, the most-polled route on the surface, a fenced read. - PsqlShareLedger.dashboard_direct_coinbase_settlement takes the direct-coinbase settlement branch off audit_bundle(), resolving the body through the existing _resolve_audit_bundle_row sha256 verification. public_api prefers both through the same duck-typed pattern as every other read model, keeping the old paths as in-memory-ledger fallbacks. Both were verified against real Postgres to return exactly what they replace, including multi-program recipients, negative balances, and quoted recipient ids. The new service is read-only in three independent ways: PsqlShareLedger gains read_only=True, which skips writer-lease acquisition and swaps the writer lock for a gate that refuses to be acquired at all; the audit artifact store gains read_only=True so it holds no publication lock and works against the :ro volume mount; and the container receives no writer, signing, or block-submission configuration. It refuses to start without PRISM_PUBLIC_STRATUM_URL (the fallback would advertise 127.0.0.1:3340 to miners) or on the in-memory ledger (whose missing dashboard_* read models would send public_api's fallbacks back onto writer-lock reads). Staleness becomes a contract, following observability.py's cached /metrics precedent: Endpoint gains max_staleness_seconds, derived as max(3 * (cache_ttl + underlying_cache), 15) rather than hand-picked, and every response publishes X-Prism-Staleness-Budget-Seconds beside Age and returns 503 rather than serve past it. /public/v1/artifacts/{sha256} is exempt via an explicit immutable_content flag. AuditHttpFacade's lifecycle machinery is untouched; audit_http no longer imports public_api at all, and an unknown /public/v1 request reaches its ordinary unknown-endpoint 404. Co-Authored-By: Claude Opus 5 <[email protected]> * Apply the PR #152 review fixes: deployment seam, stratum env, doc claims REQUEST_CHANGES findings from the Fable review of the public read tier extraction, applied on top of the extraction rebased onto the hardened endpoint-registry base: - Blocker 1: make up-prism-pool and every mainnet runbook bring-up path (config/pull/up service lists and the lane table) started only the coordinator, so a pool brought up through the documented seam had no public API at all. prism-public-api is now part of each of them. - Blocker 2: PRISM_STRATUM_PORT and PRISM_STRATUM_HIGHDIFF_PORT never reached the prism-public-api container, so the rendered /public/v1/mining-configuration silently dropped the High-diff endpoint the coordinator was actually listening on. Both now pass through the compose environment; the compose-profile suite pins the pass-through and a contract-equality case pins the High-diff endpoint in the served body against public_api.dispatch with the env set. - Should-fix 3: the dashboard README told operators to raise a route's staleness budget alongside its cache TTL, but no budget knob exists -- the budgets are constants in lab/prism/endpoint_registry.py. The paragraph now names the cache TTL knobs that do exist and says the registry constant is what changes with them. - Should-fix 4: the extraction moved the process, not the read-replica back-end, so the read-service test docstring no longer equates the move with all of issue #145; the replica remains a follow-up and the service still reads the primary Postgres. Co-Authored-By: Claude Fable 5 <[email protected]> * Carry #154's content-addressed artifact bytes into the extracted read tier Rebasing the read-tier extraction onto 2.x.x put it on top of #154, which landed while this PR was in review. Git merged the two textually, but the result was semantically broken in both directions: - audit_http kept #154's `public_api.RawJsonBody` branch in write_json while the extraction removed the public-API import, so every audit response raised NameError. GET /public/v1/artifacts/{sha256} moved out of this listener, so no route reaching it can carry pre-serialized bytes: the branch is dead here and is removed, restoring the module's import isolation. - public_read_service.write_json re-serialized every payload with sorted keys and a trailing newline. The artifacts route moved into this process, so #154's fix silently regressed: sha256(response body) would no longer match the advertised artifact hash. The RawJsonBody branch moves here with the route it serves. The two byte-exactness tests #154 added now exercise the extracted handler rather than the coordinator's audit handler, which is what pins the regression: they fail without the branch above. --------- Co-authored-by: Alex <[email protected]> Co-authored-by: Claude Opus 5 <[email protected]> Co-authored-by: Alex <[email protected]>
Problem
GET /public/v1/artifacts/{sha256}returns a document whose SHA-256 is not the requested hash, so no external verifier can confirm any artifact byte-for-byte. The hash side and the serve side use different serializers:canonical_json_text()=json.dumps(payload, sort_keys=True, separators=(",", ":"))(share_ledger.py)json.dumps(payload, sort_keys=True)+ trailing\n— the genericwrite_jsonpathpublic_api.artifact()returned a parsed dict, so the exact hashed bytes were lost before the response was written.Mainnet reproduction (2026-08-19), artifact
b3db0a91406f4288da5985fb708fc1da3749f037275845ad920a346421a8c163(qbit.prism.ctv-fanout-manifest.v1, 8,860 bytes served):6c1df2a6ab0eb220…json.dumps(d, sort_keys=True)(served minus trailing newline)2adcb1149b5e2db9…canonical_json_text(d)b3db0a91406f4288…← advertisedGET /public/v1/artifacts/6c1df2a6…→ 404, confirming the store is keyed by the canonical digest and only the response is re-serialized.This affects every artifact kind, including CTV manifests and manifest-sets — they are only "unaffected" for a verifier that re-canonicalizes the parsed document; byte-level verification (
sha256(response body) == {sha256}) fails for all kinds. Tracking issue: SwapLabsInc/qbit-mining-bootstrap#182 (scope corrected there accordingly).Fix
Serve the exact bytes the hash was computed over. The ledger already persists them for the manifest kinds —
manifest_json/manifest_set_jsonare written next to the JSONB copies at record time, by the same call that computes the hash:share_ledger: newdashboard_public_artifact_canonical_json()on both backends returns the persisted canonical text for CTV manifests and manifest sets,Nonefor audit bundles.public_api.artifact(): verifiessha256(canonical bytes) == {sha256}and returns them as aRawJsonBody; any mismatch (a store-integrity fault) falls back to the legacy re-serialized response, so the endpoint can never serve "exact" bytes that contradict the content address.audit_http.write_json: writesRawJsonBodyverbatim — no re-serialization, no trailing newline,Content-Type: application/json. Cache headers (immutable, CDN TTLs) and the public response cache behave as before, andContent-Lengthnow equals thebyte_lengthadvertised by settlementartifact_links.No hash definition changes; historical hashes stay valid. The response parses to the identical document (keys were already sorted on both sides — only separators and the trailing newline differ), so dashboard clients are unaffected.
What is and isn't covered
qbit-prism-audit-canonicalize); those bytes are produced and verified at persist time but not stored (the external body store writes compact v2/segmented layouts). Bundles keep the legacy response, and the regression suite pins that gap with anexpectedFailuretest to be flipped by the follow-up. Proposed follow-up (detailed in the tracking issue): persist the canonical bundle bytes at hash time — they are already in hand there — rather than re-deriving tens of MB via subprocess per request on a public endpoint, which would also silently invalidate historical hashes if struct declaration order ever changed.Other endpoints checked: settlement-artifacts and fanout responses embed only links (
sha256+url+byte_length), never artifact bodies. The/audit/*bundle and manifest-set endpoints return metadata envelopes, which are not content-addressed; their embedded*_jsonstring fields already carry the canonical text.Tests
PublicArtifactByteExactnessTests(the regression coverage that was missing): assertssha256(response body) == advertised hashfor each manifest kind over real HTTP; byte-exactness across public-cache hits (with theimmutableCDN header); uppercase-hash request paths; tampered canonical text falling back to legacy serving; audit-bundle byte-exactness asexpectedFailure.persist_ctv_fanout_manifest_set→ HTTP responses hash to the advertised digests for both kinds.canonical_json_text(...); Psql getter readsmanifest_set_json/manifest_json(canned-query harness).Full
unittestdiscovery matches the base commit (thetest_prism_job_builderspool/splice failures on macOS are pre-existing and unrelated; verified identical on2.x.xHEAD without this change).Release-line note
Production runs the 1.x line, so this fix does not reach the live pool from 2.x.x alone. The commit cherry-picks onto
origin/1.x.xwith one mechanical relocation — thewrite_jsonhunk lands inprism_coordinator.py's handler (audit_http.pydoes not exist there) — and the full dashboard + ledger test modules pass on that branch (verified locally). Backport PR ready to open on request.🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.