Skip to content

2.x.x: bound PRISM payout-window database decoding - #238

Merged
kiwidream merged 5 commits into
2.x.xfrom
fix/prism-236-window-decoding-20260906
Sep 6, 2026
Merged

kiwidream merged 5 commits into
2.x.xfrom
fix/prism-236-window-decoding-20260906

Conversation

@kiwidream

@kiwidream kiwidream commented Sep 6, 2026 •

Copy link
Copy Markdown
Member

Large payout-window snapshot and delta reads currently return one json_agg value. Decoding that whole window can prevent the lease-monitor thread from running for hundreds of milliseconds. Return one JSON object per row and decode/convert results in batches of 512 records on both PostgreSQL backends.

The existing selection predicates, weighted cutoff, ordering, return type and read-gate attribution are preserved. The native client consumes one buffered SELECT with fetchmany; the psql backend validates the child process result before parsing an anonymous spool file line by line. Deadline checks cover initial decoding, batch boundaries, empty results and the final partial batch. Retry-safe connection failures discard partial results and retry the complete statement within the original budget.

Validation:

  • Local Python 3.14: 305 share-ledger and issue-224 attribution tests passed; changed shell scripts pass syntax checks; git diff --check passed.
  • Linux worker: focused suites passed. PostgreSQL ledger and scale gates passed using external psql with disposable databases. The native integration gate body passed against PostgreSQL 16; its Docker wrapper hit a child-process permission failure reproduced on the unchanged base.
  • PostgreSQL regression additions compare bounded, unbounded, empty and delta reads against the previous aggregate projection and verify that a concurrent append during decoding is absent from the entire in-flight snapshot.

Shared-host Python 3.12 measurements reduced worst monitor delay from 750–950 ms to 176–260 ms at 210,000 shares, and from 1.4–1.6 s to 342–484 ms at 400,000 shares. Native reads cost roughly 30% more caller-thread CPU; peak memory and server execution time fell. Details and reproduction commands are in tests/perf/window_ledger_decode_latency.md.

The 250 ms engineering target remains unmet in some cases; the report attributes the residual to GC collections. Production-image, combined heartbeat/recovery and soak validation remain outstanding. This change covers snapshot/delta reads; candidate-intent SQL serialization remains separate work.

Part of #236. Companion changes: pipe transport #237 and window serialization #239. This PR does not close the incident issue.

Integration validation: this branch includes merged #237 and the reviewed #239 changes so CI tests the complete three-PR tree at 6174754. The shared test-file conflict was resolved by retaining both appended blocks unchanged. This tree passed 436 local Python 3.14 tests (2 platform skips); full GitHub CI passed, including 3,374 Python tests (2 skipped), PostgreSQL gates, Rust tests and both payout-window parity adapters. #239 is now merged as a4d4b11. The final ancestry reconciliation at 4335aee has exactly the same Git tree as tested 6174754; GitHub CI also passed on that final commit. The separate Rust paging fix is tracked in #240.

kiwidream and others added 2 commits September 6, 2026 08:53
…ends (#236)

The coordinator's payout-window snapshot and delta returned one json_agg
value the size of the whole window, and decoding it was a single C call
that never released the GIL: at the incident's ~210k shares the lease
monitor thread went unscheduled for the whole decode. Both reads now
project one JSON object per row from the unchanged selection CTEs, and
each backend converts the rows in 512-record batches, rechecking the
caller's absolute operation deadline and stamping liveness between
batches.

- LedgerSqlPort gains run_json_rows; _NativePostgresClient implements it
  over fetchmany with run_json's connection borrowing, SET LOCAL deadline
  transaction (committed before decoding starts), OperationalError
  translation and once-only retry that discards partial rows and re-runs
  the complete SELECT inside the original deadline.
- The psql backend spools stdout to an unnamed temporary file, validates
  exit status and stderr exactly as _run_sql does, kills and reaps a timed
  out child, and parses the spool one line per row. _psql_invocation is
  shared by both paths so flags, session guards and deadlines cannot
  drift.
- snapshot_at_job_issue and snapshot_between_job_issues keep their SQL
  selection, ordering, weighted crossing row, eligibility predicates,
  returned record-list API, read-slot admission and #224 attribution
  (payout_window_snapshot / payout_window_delta); only the outer
  projection and the decode path changed. Mutations and lease statements
  keep run_json unchanged.
- Legacy subclass seams (_run_json and _run_sql overrides) and the
  concurrency-harness fake port are updated explicitly so no backend
  bypasses the row path by accident.
- Every decode path checks the statement and operation deadlines before
  decoding starts, between batches, and before publishing, so a trailing
  partial batch or a result shorter than one batch cannot return after
  the budget.

Tests: 25 new unit tests (real fake-psql child process for the subprocess
path; fake driver for the native client; virtual-clock deadline and
progress checks; SQL shape); the issue-224 differential control gains a
row-result twin; both PostgreSQL gates compare every window variant
against the pre-change json_agg oracle and the native gate proves a share
appended mid-decode is absent from the in-flight snapshot.
tests/perf/window_ledger_decode_latency.py measures baseline vs patch at
210k and 400k shares with a wake-lateness monitor beside the read; results
in tests/perf/window_ledger_decode_latency.md (shared-host figures: worst
monitor wake lateness during a read 750-950 ms -> 176-260 ms at 210k and
1.4-1.6 s -> 342-484 ms at 400k on both backends, no wake-up over 500 ms
with the patch, server time and peak RSS down; the residual stalls are
gen-2 GC collections over the returned records, attributed with a probe
and left as a coordinator-level follow-up).

Refs #236 (does not close it: PRs 2 and 3 of the plan and the dedicated
environment release gates remain).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WkTwwTmMgLDe9WDY3rnrmh
Every whole-window JSON call on the payout-window paths -- the daemon
prepare_window request, the audit-builder compact tail (spool, in-memory
fallback and one-shot), the digest of a freshly read share list, the daemon
mirror's lazy parse, the found-block candidate identity digest and the
one-shot canonical payload -- is replaced by batched encoding or
record-at-a-time parsing that produces byte-identical output while bounding
any one C call to 512 records or one 64 KiB decode chunk, so the writer-lease
monitor thread can run between batches instead of waiting behind a
whole-window json.dumps/json.loads.

- lab/prism/share_json_stream.py: new leaf helper (batched array/object
  encoders, streamed canonical digest, ShareArrayJsonSequence view,
  bounded list release).
- share_ledger.py: page encoding through the helper; _walk_canonical_items
  (incremental UTF-8 decode + raw_decode per record, shared key strings,
  strict layout checks); DaemonShareJsonSequence parses record by record and
  publishes only after the count check; block_candidate_identity_sha256
  streams shares_json.
- bundle_compiler.py: compact tail as bounded chunks (compact_tail_chunks)
  written identically by spool, daemon in-memory fallback and one-shot;
  prepare_payout_window streams the request and retires the daemon on a
  half-written line; the canonical one-shot payload streams its arrays.
- payout_state.py / job_bundle.py: share-list digests go through the
  streaming view; transient per-share lists released in bounded slices.
- metrics.py: compact-json byte accounting via compact_json_bytes.
- tests: byte-parity, malformed/chunk-boundary parse, fault injection
  (unencodable record mid-request, daemon death mid-request), candidate
  digest parity, spool/in-memory equality.
- tests/perf: --latency-probe mode with a lease-monitor-cadence lateness
  thread, GC attribution and the real daemon round trip; report section 9
  records the shared-host measurements and the Rust paging finding.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AFvDqz6xwHRWxCWwJPiXvT
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 6, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-06T13:59:36.911296Z 4335aee New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Retain both appended share-ledger test blocks when combining PRs 238 and 239.
Keep the previously validated combined source tree unchanged while adopting the squash merge of PR 239.
@kiwidream
kiwidream merged commit 0bc7fa6 into 2.x.x Sep 6, 2026
11 checks passed
@kiwidream
kiwidream deleted the fix/prism-236-window-decoding-20260906 branch September 6, 2026 14:03
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