fix(acquisition): preserve purchase journal bytes on replay - #459
Conversation
|
Warning Review limit reached
Next review available in: 41 minutes You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (5)
Walkthrough
ChangesPurchase snapshot isolation
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Caller
participant CaseDevPurchaseJournal
participant TemporarySQLite
participant CanonicalFiles
Caller->>CaseDevPurchaseJournal: request read-only purchase snapshot
CaseDevPurchaseJournal->>CanonicalFiles: acquire shared lock
CaseDevPurchaseJournal->>TemporarySQLite: copy ledger, WAL, and journal files
CaseDevPurchaseJournal->>TemporarySQLite: validate and query in read-only mode
CaseDevPurchaseJournal-->>Caller: return authenticated snapshot
CaseDevPurchaseJournal->>CanonicalFiles: verify unchanged namespace on close
Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
tests/test_case_dev_purchase.py (1)
156-168: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for the mutation detector in
close().This test proves the happy path: the canonical files do not change, so
close()passes. No test drives the failure branch atcase_dev_purchase.pylines 1687-1691. That branch is the fail-closed control of this PR. It raisesCaseDevPurchaseLedgerErrorwhen the canonical namespace changes during a read-only audit.Add a test that mutates a canonical file inside the
with CaseDevPurchaseJournal(..., read_only=True)block, then asserts that leaving the block raisesCaseDevPurchaseLedgerErrorwith the message about filesystem state.The rejection of
allow_create=Truecombined withread_only=Trueat line 1558 is also uncovered.Do you want me to generate both tests?
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/test_case_dev_purchase.py` around lines 156 - 168, Add tests in tests/test_case_dev_purchase.py covering both read-only safeguards: mutate a canonical file inside the with CaseDevPurchaseJournal(..., read_only=True) block and assert exiting raises CaseDevPurchaseLedgerError with the filesystem-state message, then add coverage asserting read_only=True with allow_create=True is rejected at journal construction. Reuse the existing journal, canonical-path, and assertion helpers from the surrounding tests.legalforecast/ingestion/case_dev_purchase.py (1)
2873-2906: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winAlign
purchase_state_sha256()withauthenticated_snapshot()and avoid duplicate digest inputs.Both methods hash the current JSON-serializable purchase rows plus
committed_amount_usd, while_purchase_operation_record()exposes raw fields from the unknown public material recovery join. Makepurchase_state_sha256()reusecommitted_amount_usdand the canonical operation-row shape instead of defining the digest payload separately.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@legalforecast/ingestion/case_dev_purchase.py` around lines 2873 - 2906, Update purchase_state_sha256() to derive its digest payload from the same committed_amount_usd value and canonical operation-row representation used by authenticated_snapshot(). Reuse the existing authenticated_snapshot() or shared canonicalization path rather than independently hashing raw _purchase_operation_record() fields, while preserving the existing cycle and policy identifiers in the digest.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@legalforecast/ingestion/case_dev_purchase.py`:
- Around line 2882-2891: Sort the candidate IDs before iterating in the per-case
cap validation loop around _read_candidate_committed_amount, replacing the
unordered set iteration with deterministic ordering. Preserve the existing cap
comparison and CaseDevPurchaseLedgerError behavior while ensuring the same
exceeding candidate is reported consistently.
In `@tests/test_case_dev_purchase.py`:
- Around line 136-142: Update the read-only probe around main_file_only to
explicitly close the SQLite connection after the query, using contextlib.closing
or an explicit main_file_only.close() while preserving the existing
pytest.raises assertion.
---
Nitpick comments:
In `@legalforecast/ingestion/case_dev_purchase.py`:
- Around line 2873-2906: Update purchase_state_sha256() to derive its digest
payload from the same committed_amount_usd value and canonical operation-row
representation used by authenticated_snapshot(). Reuse the existing
authenticated_snapshot() or shared canonicalization path rather than
independently hashing raw _purchase_operation_record() fields, while preserving
the existing cycle and policy identifiers in the digest.
In `@tests/test_case_dev_purchase.py`:
- Around line 156-168: Add tests in tests/test_case_dev_purchase.py covering
both read-only safeguards: mutate a canonical file inside the with
CaseDevPurchaseJournal(..., read_only=True) block and assert exiting raises
CaseDevPurchaseLedgerError with the filesystem-state message, then add coverage
asserting read_only=True with allow_create=True is rejected at journal
construction. Reuse the existing journal, canonical-path, and assertion helpers
from the surrounding tests.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 846326fb-4dc1-49bd-9c34-96598188722e
📒 Files selected for processing (2)
legalforecast/ingestion/case_dev_purchase.pytests/test_case_dev_purchase.py
There was a problem hiding this comment.
Pull request overview
This PR hardens purchase-ledger “read-only audit” by introducing a byte-preserving replay path: instead of opening the canonical SQLite files directly (and potentially triggering WAL/checkpoint side effects), it copies the committed SQLite namespace into a private temp directory, replays/validates on the copy, and verifies the canonical on-disk bytes/mtimes/identities did not change during the audit.
Changes:
- Add
read_only=Truemode toCaseDevPurchaseJournalthat acquires a shared lock, snapshots reserved SQLite paths into a private temp namespace, runs integrity/policy/schema checks, enforcesPRAGMA query_only=ON, and compares filesystem identity on close. - Refactor
read_case_dev_purchase_snapshot()to route through the journal’s read-only mode and a newauthenticated_snapshot()helper (caps checks +purchase_state_sha256). - Add a regression test ensuring WAL-backed terminal state is replayed correctly without mutating canonical db/wal/shm/journal bytes, and that attempted writes are rejected.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| legalforecast/ingestion/case_dev_purchase.py | Introduces the byte-preserving read-only journal path and consolidates snapshot authentication logic. |
| tests/test_case_dev_purchase.py | Adds coverage for WAL replay + immutability verification and write rejection in read-only mode. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 5 out of 5 changed files in this pull request and generated no new comments.
Suppressed comments (3)
legalforecast/ingestion/case_dev_purchase.py:3723
_purchase_snapshot_filesystem_identityalso opens files withO_NOATIME, which can fail withEPERM/EACCESdepending on file ownership/capabilities. Currently that propagates as a rawOSErrorrather than aCaseDevPurchaseLedgerError, making read-only audit failures harder to diagnose.
descriptor = os.open(path, _read_only_snapshot_open_flags())
legalforecast/ingestion/case_dev_purchase.py:3674
_copy_regular_single_link_fileopens the source file usingO_NOATIME, which can raisePermissionError/EPERMunless the current user owns the file (or has CAP_FOWNER). Right now that bubbles up as a rawOSError, which breaks the otherwise consistentCaseDevPurchaseLedgerErrorsurface for read-only audits and makes failures harder to interpret.
This issue also appears on line 3723 of the same file.
source_flags = _read_only_snapshot_open_flags()
source_fd = os.open(source, source_flags)
destination_fd: int | None = None
legalforecast/ingestion/case_dev_purchase.py:3707
- In
_copy_regular_single_link_file'sfinally, ifos.close(destination_fd)raises,source_fdwill never be closed, leaking a file descriptor (and contradicting the PR goal of unconditionally releasing descriptors). Use a nestedtry/finallysosource_fdis always closed.
finally:
if destination_fd is not None:
os.close(destination_fd)
os.close(source_fd)
|
[awt-judge] Opus decision Decision: approve_as_is |
## Summary - Bind the frozen terminal purchase result and run card into replacement-corpus materialization so the four authenticated unavailable docket decisions become audit-only omissions. - Route the exact seven-document ranked-reserve tranche through its pinned projection digest and direct CourtListener purchase authority, with no obsolete clearance-frontier or broker dependency. - Accept only the two closed producer encodings used by authenticated target selections; arbitrary nonproducer ordering remains fail-closed. ## Validation - Exact head: `bb723612e155d6f84e00f12b5060e49f23a7d916` - Hosted Python quality gates and all required checks passed on the functional parent; successor checks are running for two review-wording corrections. - Ruff, Pyright, and 97 focused tests passed locally on the exact successor head. - Provider-free render/preflight produced 19 stages and stopped at `execution_not_requested` without provider or paid activity. - Post-#459 real-artifact canary preserved the full canonical purchase-journal namespace byte-for-byte: database SHA-256 remained `54bf7d866fa405c9c209aef9e7a89d32296cde33e93d90e3b7857c6f7c678f78`. - Canary replay authenticated logical purchase state `c7fa950...`, exactly four audit-only decision omissions, and the expected 323 selected / 4 omitted / 319 materialized / 3 residual terminal candidates / 7 terminal candidates partition. ## Scope No provider request, paid purchase, evaluation, freeze, or dispatch occurred. The former dependency on PR #459 is resolved: #459 merged as `5b3efdb91fc40bfb6c9843efc8ffa0a6daa89a8c`, and this PR is restacked directly on that merge. Bead: `LegalForecastBench-5qd6.118.16.11`
## Summary - allow the exact-100 successor's authenticated empty pre-recovery purchased manifest to derive paid scope from final-selection gap identities - subtract only verifier-owned terminal decision omissions and bind their source artifacts and partition into the consolidation run card - filter historical closed-tranche material to the final active scope while rejecting missing, duplicate/rebound, uncleared, unledgered, or inconsistent records - route terminal-authority journal replay through the byte-preserving read-only API landed in #459 and integrate the terminal-recovery contract landed in #460 ## Validation - `uv run pytest -q tests/test_replacement_recovery_consolidation.py tests/test_cohort_document_materializer.py tests/test_unknown_public_recovery.py` — 95 passed - `uv run ruff format --check legalforecast/cli.py tests/test_replacement_recovery_consolidation.py` - `uv run ruff check legalforecast/cli.py tests/test_replacement_recovery_consolidation.py` - `uv run pyright` — 0 errors - `uv run pytest -q` — 6,157 passed, 13 skipped No live purchase ledger, provider, paid acquisition, evaluation, freeze, or dispatch operation was performed. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added support for authenticated terminal omission inputs during replacement recovery. * Recovery now records verified source snapshots and input locations. * Added replay handling for terminal omission metadata. * **Bug Fixes** * Strengthened validation of paid-document coverage, ledger consistency, clearance status, and recovery gaps. * Duplicate recovery records are now rejected consistently. * Recovery now detects missing or inconsistent authority inputs and coverage data. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Summary
read_only=Truepurchase-journal mode that replays committed WAL or hot rollback-journal state only in an expendable private copyValidation
uv run ruff check legalforecast/ingestion/case_dev_purchase.py legalforecast/ingestion/replacement_purchase_approval.py legalforecast/cli.py tests/test_case_dev_purchase.py tests/test_replacement_purchase_approval.pyuv run pyrightuv run pytest -q tests/test_case_dev_purchase.py(15 passed)uv run pytest -q tests/test_replacement_purchase_approval.py(26 passed)Bead:
LegalForecastBench-5qd6.118.16.14