Repository navigation
V1-M instrument: progressive checkpoint + --resume (post-reboot-loss hardening) - #199
Conversation
A host reboot killed a 17h 6-shard registered run with zero results on disk (report-only-at-end design). Adds crash-safe per-question checkpoint jsonl (flushed per write) + --resume (seed aggregates from checkpoint, skip completed, truncate only a torn final line, fail closed on wrong-set/duplicate/mid-file corruption) + an uninterrupted-run report-equivalence test.
|
Warning Review limit reachedYou’ve reached a temporary PR review limit under our Fair Usage Limits Policy. Next review available in: 21 minutes Your organization has reached its usage spending cap. Adjust your spending cap in the billing tab. 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: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (5)
📝 WalkthroughWalkthroughThe harness now supports durable per-question JSONL checkpoints and resumed execution. It validates checkpoint configuration, selected IDs, and records, recovers torn final lines, restores aggregates, skips completed questions, and exposes resume support through the CLI. ChangesCheckpoint and Resume Support
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant CLI
participant run_harness
participant CheckpointFile
participant Evaluator
CLI->>run_harness: pass selected IDs and resume options
run_harness->>CheckpointFile: load and validate checkpoint
run_harness->>Evaluator: evaluate unfinished question
Evaluator-->>run_harness: return question result
run_harness->>CheckpointFile: append and flush result
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f8b635a3a9
ℹ️ 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.
Actionable comments posted: 7
🤖 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 `@benchmarking/longmemeval.py`:
- Around line 1670-1693: The _question_checkpoint_record helper mutates the
scored payload by removing ingest_ms and hybrid_rerank.rerank_mode. Avoid
mutating the caller-owned dictionary by copying the relevant scored structures
before extracting these fields, while preserving the returned checkpoint record
contents and existing behavior for None.
- Around line 1847-1849: Update the checkpoint_file initialization around
checkpoint_path.open so that, when resume is false and an existing checkpoint
file is non-empty, a warning is logged before opening it in write mode. Preserve
append behavior for resume runs and the current creation behavior for missing or
empty checkpoints.
- Around line 1885-1889: Update the checkpoint-writing block after
checkpoint_file.flush() to call os.fsync(checkpoint_file.fileno()), ensuring
each serialized record is synchronized to durable storage before continuing.
- Around line 1727-1748: Within the guarded arm-metrics aggregation block,
validate every numeric recall, nDCG, and latency value before appending it:
accept only int or float values, explicitly reject bool and null/string values,
and raise the existing question-specific ValueError for invalid metrics.
Preserve the original validated numeric values without converting integers to
floats, including values stored in bucket and overall aggregates.
In `@scripts/lcm_longmemeval.py`:
- Around line 240-242: Update the argparse help text for the --resume option in
scripts/lcm_longmemeval.py to mention that resuming with a smaller --limit than
the original run is unsupported and fails closed. Keep the existing checkpoint
wiring and ValueError-to-SystemExit behavior unchanged.
In `@tests/test_longmemeval_medium_r2_core.py`:
- Around line 298-331: Expand coverage in the resume/checkpoint tests around
_run_with_checkpoint to include mid-file JSON corruption and duplicate
checkpoint question IDs, asserting ValueError and that evaluation is not called;
add abstention checkpoint round-trip coverage for _question_checkpoint_record
and _accumulate_question_checkpoint; and add a torn-tail case where the
incomplete record belongs to a non-final selected question, verifying truncation
preserves only retained records and reruns the affected question.
- Line 6: Update _scored to handle non-numeric question IDs without exposing a
confusing int conversion ValueError, while preserving distinct per-question
outputs; use a string-safe derivation or explicit validation with a clear
message for unsupported IDs.
🪄 Autofix (Beta)
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: ASSERTIVE
Plan: Pro
Run ID: 44704ea4-56da-4365-a417-108ea10c5014
📒 Files selected for processing (5)
benchmarking/longmemeval.pyscripts/lcm_longmemeval.pytests/test_longmemeval_medium.pytests/test_longmemeval_medium_r2_cli.pytests/test_longmemeval_medium_r2_core.py
📜 Review details
⏰ Context from checks skipped due to timeout. (4)
- GitHub Check: test (3.11)
- GitHub Check: test (3.12)
- GitHub Check: test (3.14)
- GitHub Check: test (3.13)
🧰 Additional context used
🪛 ast-grep (0.45.0)
tests/test_longmemeval_medium_r2_core.py
[info] 292-292: use jsonify instead of json.dumps for JSON output
Context: json.dumps(resumed, indent=2, sort_keys=True)
Note: [CWE-116] Improper Encoding or Escaping of Output.
(use-jsonify)
[info] 292-294: use jsonify instead of json.dumps for JSON output
Context: json.dumps(
uninterrupted, indent=2, sort_keys=True
)
Note: [CWE-116] Improper Encoding or Escaping of Output.
(use-jsonify)
benchmarking/longmemeval.py
[info] 1886-1886: use jsonify instead of json.dumps for JSON output
Context: json.dumps(record, sort_keys=True, separators=(",", ":"))
Note: [CWE-116] Improper Encoding or Escaping of Output.
(use-jsonify)
🔇 Additional comments (10)
benchmarking/longmemeval.py (5)
76-76: LGTM!
628-631: LGTM!
1620-1667: Loader design is sound; note the in-place mutation ordering.The loader fails closed on mid-file corruption, wrong selection, and duplicate IDs, and only truncates a torn final line. One small caveat: the truncate and the trailing-newline append happen during the scan, so the on-disk file is modified even if a later line then raises
ValueError. The truncation path breaks immediately, so this only affects the newline append, which is idempotent and harmless. No change required.
1765-1767: Resume input validation reads correctly.The
Sequencefallback avoids consuming a generator, the streaming case fails with an explicit message, and uniqueness is enforced before the checkpoint is loaded. The checkpoint is only read whenresumeis set and the file exists.Also applies to: 1779-1798
1833-1845: Skip-and-verify loop logic is correct.
consumed_countincrements for skipped questions, so the existingquestion_countcheck still holds on resume. Checkpoint records replay in file order before the remaining questions, which preserves sample ordering and therefore report equivalence. Theobserved_question_ids != selected_idscheck runs after the loop and reports both missing and extra IDs.One note for the static analysis hint on Line 1886: the
use-jsonifyrule is a Flask web-response rule. It does not apply to JSONL file serialization. Ignore it.Also applies to: 1851-1884, 1890-1901
Source: Linters/SAST tools
scripts/lcm_longmemeval.py (2)
30-30: LGTM!Also applies to: 102-107
202-202: Selection sources are consistent with the iterators.The direct path derives IDs from the already-materialized
questionslist. The prepared path usesselected_question_ids(limit=args.limit), which applies the same_selected_entrieslimit asiter_questions(limit=args.limit). The ID set and the iterated set therefore match, which is what the harness end-of-run equality check requires.Also applies to: 217-217
tests/test_longmemeval_medium_r2_cli.py (1)
77-79: Test double matches the real signature.
selected_question_ids(self, *, limit=None)mirrorsPreparedDataset.selected_question_ids, including the keyword-onlylimit. The empty return is consistent withquestion_count = 0.tests/test_longmemeval_medium_r2_core.py (1)
239-254: Strong equivalence coverage.Pinning
time.strftimeis the right way to make the two reports byte-comparable. Assertingevaluated == ["q2"]proves that completed questions are skipped rather than silently re-scored, and the serialized-bytes assertion locks the report format. The flush test correctly proves the write happens before the next question, not at close time.Also applies to: 257-295
tests/test_longmemeval_medium.py (1)
321-326: LGTM!
…tch/headerless), torn-vs-corrupt newline distinction, per-write fsync, refuse non-empty checkpoint without --resume, no-mutation record helper, byte-strict report equivalence, 6 fail-closed tests
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 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 `@benchmarking/longmemeval.py`:
- Around line 1885-1905: Validate the resume configuration before the
checkpoint_path-gated block: when resume is True and checkpoint_path is None,
raise a clear ValueError instead of proceeding with an empty checkpoint_records
set. Preserve the existing checkpoint validation and loading behavior for
callers that provide checkpoint_path.
- Around line 1949-1953: After creating a new checkpoint in the checkpoint_path
open block, fsync checkpoint_path.parent to persist the directory entry before
writing records; perform this only when resume is false, and guard directory
opening/fsync with OSError handling for Windows compatibility.
In `@tests/test_longmemeval_medium_r2_core.py`:
- Around line 495-539: Add coverage for abstention checkpoint round-tripping,
preferably by including an abstention question in the resume-equivalence
scenario or adding a dedicated test. Use the existing _question helper and its
is_abstention setup, then verify resumed and fresh runs produce identical
reports, including abstention_excluded, while exercising
_question_checkpoint_record with scored=None and _accumulate_question_checkpoint
without adding arm samples.
- Around line 442-446: Extract the repeated evaluate_question guard into a
shared _never_score(monkeypatch) helper in this test module, with a nested
callable that raises AssertionError("must not score"). Replace all five
generator-throw monkeypatch blocks with calls to _never_score(monkeypatch),
preserving the existing behavior.
- Around line 100-111: Update the _header_record helper to use
lme._embedding_batch_size() for the embedding_batch_size default instead of
lme.EMBED_BATCH_SIZE, while preserving override handling through
bindings.update(overrides).
🪄 Autofix (Beta)
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: ASSERTIVE
Plan: Pro
Run ID: 92012e06-c73a-489a-8216-cb96b3d16eaf
📒 Files selected for processing (2)
benchmarking/longmemeval.pytests/test_longmemeval_medium_r2_core.py
📜 Review details
⏰ Context from checks skipped due to timeout. (4)
- GitHub Check: test (3.13)
- GitHub Check: test (3.11)
- GitHub Check: test (3.14)
- GitHub Check: test (3.12)
🧰 Additional context used
🪛 ast-grep (0.45.0)
tests/test_longmemeval_medium_r2_core.py
[info] 116-116: use jsonify instead of json.dumps for JSON output
Context: json.dumps(record, sort_keys=True, separators=(",", ":"))
Note: [CWE-116] Improper Encoding or Escaping of Output.
(use-jsonify)
[info] 350-350: use jsonify instead of json.dumps for JSON output
Context: json.dumps(uninterrupted, indent=2, sort_keys=True)
Note: [CWE-116] Improper Encoding or Escaping of Output.
(use-jsonify)
[info] 353-353: use jsonify instead of json.dumps for JSON output
Context: json.dumps(resumed, indent=2, sort_keys=True)
Note: [CWE-116] Improper Encoding or Escaping of Output.
(use-jsonify)
[info] 499-499: use jsonify instead of json.dumps for JSON output
Context: json.dumps(_header_record(), sort_keys=True, separators=(",", ":"))
Note: [CWE-116] Improper Encoding or Escaping of Output.
(use-jsonify)
[info] 501-501: use jsonify instead of json.dumps for JSON output
Context: json.dumps(valid_record, sort_keys=True, separators=(",", ":"))
Note: [CWE-116] Improper Encoding or Escaping of Output.
(use-jsonify)
benchmarking/longmemeval.py
[info] 1740-1740: use jsonify instead of json.dumps for JSON output
Context: json.dumps(record, sort_keys=True, separators=(",", ":"))
Note: [CWE-116] Improper Encoding or Escaping of Output.
(use-jsonify)
🔇 Additional comments (12)
benchmarking/longmemeval.py (6)
24-24: LGTM!Also applies to: 78-78
1622-1642: LGTM!
1645-1668: LGTM!
1671-1736: LGTM!
1739-1744: LGTM!Also applies to: 1747-1771
1955-2002: LGTM!tests/test_longmemeval_medium_r2_core.py (6)
5-5: LGTM!Also applies to: 86-97, 114-121
266-296: LGTM!
299-307: LGTM!
346-356: LGTM!
359-393: LGTM!Also applies to: 396-415
418-433: LGTM!Also applies to: 458-492
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6f5620c647
ℹ️ 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".
…nt fsync; abstention round-trip test) + content-hash embedding cache (5.04x measured dedupe: env-gated SQLite WAL cache, determinism-probe subcommand, prewarm CLI, cache test suite)
|
Scope addition + correction. The last three thread replies cited an empty commit sha — a shell-gating bug on my side (the fix commit hadn't landed when the replies posted; the failure class is now documented in our process memory). The actual fixes are in eaea1c5, which also adds the second restart-hardening piece: a content-hash embedding cache (measured 5.04x session dedupe across prepared-m: 250,948 instances / 49,803 unique). Env-gated ( |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: eaea1c5083
ℹ️ 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".
…eckpoint header; parent-dir sync covers cache DB; empty-resume skips provider init; restored-metric type validation; env-gated cache stats (golden untouched); Windows fsync guard; prewarm warm-up
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b2b0f9b2a1
ℹ️ 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".
| "embeddings_enabled": embeddings_enabled, | ||
| "dataset_label": dataset_label, | ||
| "reuse_db_template": reuse_db_template, | ||
| "embedding_batch_size": embedding_batch_size, |
There was a problem hiding this comment.
Bind the chunk threshold into checkpoint headers
When a run started with LCM_CHUNK_MIN_CONVERSATIONAL_TOKENS is resumed after that variable changes or disappears—for example, after rebooting into a different shell environment—this header still validates. evaluate_question invokes iter_message_chunks(..., policy="conversational"), and chunking._min_conversational_tokens() reads that variable for each question, so checkpointed and newly scored questions can use different chunk corpora while their chunk-vector and hybrid metrics are aggregated together. Fresh evidence beyond the earlier configuration-binding fix is that the effective chunk threshold remains absent from bindings; persist and compare it on resume.
Useful? React with 👍 / 👎.
| if not digests: | ||
| return {} | ||
| found: dict[str, list[float]] = {} | ||
| with self._connect() as connection: |
There was a problem hiding this comment.
Close each embedding-cache connection explicitly
When the cache is enabled for a medium run, every document embedding performs this lookup and a miss opens additional connections for insertion and re-reading. A sqlite3.Connection context manager commits or rolls back but does not close the connection, so these blocks leave file descriptors to cyclic garbage collection; with thousands of chunk requests the process can reach its descriptor limit and fail mid-run with sqlite3.OperationalError. Explicitly close connections at every cache call site, for example with contextlib.closing or try/finally.
Useful? React with 👍 / 👎.
| with self._connect() as connection: | ||
| mode = str(connection.execute("PRAGMA journal_mode=WAL").fetchone()[0]) |
There was a problem hiding this comment.
Retry concurrent WAL initialization
When multiple shards start simultaneously against a new shared cache file, each constructor executes PRAGMA journal_mode=WAL; SQLite can return database is locked here despite the configured busy timeout, aborting a shard before evaluation begins. The concurrent-writer test avoids this path by constructing both cache wrappers sequentially, so it does not cover the actual first-start race. Serialize initialization or retry this PRAGMA/DDL transaction on lock errors.
Useful? React with 👍 / 👎.
The branch had merged the MAINTAINER's upstream (v0.21.0-rc2) and that was mistaken for being current. It was not current with OUR main, which carried 56 commits this branch had never seen: V1-M instrument (#199, #198), fts_prose_mode (#183), profile-scoped trajectory embeddings (#182), query views. Bidirectional, not a catch-up -- both lines developed the same files in parallel (tools.py ours=11/theirs=9, vector_store.py 6/8, store.py 5/5), and reasoning.py and requirements_compiler.py do not exist at the merge base at all. 15 files, 52 hunks. Default resolution was BOTH SIDES: ours' security parameter and theirs' feature parameter, additively. ## The leak that was in no conflict hunk Main added a resident-int8 full-corpus fast path (`resident_eligible` -> `_resident_int8_matrix` -> `_rank_resident_int8`) that sits immediately BEFORE the sign-bit prescreen block ours guards with `access_scope is None`, and mirrors that block's eligibility conditions -- without the owner guard. Git auto-merged it CLEANLY. Our guard survived while a bypass around it landed one branch earlier, with no conflict marker anywhere and nothing for a diff review to catch. The resident matrix is a whole-identity snapshot pooled and cached on (identity, data_version) only, so it cannot express a per-row owner predicate. Filtering inside it is not an option; routing around it is, exactly as ours already does for the binary prescreen. Both arms now carry `access_scope is None`. ## The trap that WAS in a conflict hunk Main refactored the message-search call to `**message_search_kwargs`, and that dict carried every field ours listed EXCEPT `access_scope`. Taking main's side verbatim silently unscopes message search -- every principal reads every other principal's memory, with all tests green. Carried into the new form. ## Reconciling two independent models of reasoning.py `resolve_occurrence_time_with_trust(session_date=...)` served two roles at once: theirs' caller-DECLARED anchor (the term the sidecar is compared against to detect disagreement) and the term the occurrence is RESOLVED against. Ours needs the resolution anchor to be host-derived and a caller's declaration to be evidence-free. No single ordering satisfies both: map-first defeats the override check entirely, because tools.py sources that map from `engine._session_occurrence_dates` -- the sidecar's own attribute -- so anchor and sidecar were always equal; declared-first lets a caller relabel a stored observation. Split into two parameters, precedence sidecar > trusted > declared. Main's `"auto"` interval-unit sentinel is replaced by `interval_unit_fixed`, so "the plan's unit" and "the reported unit" decouple and both sides' tests hold. ## Verified, not asserted real-data battery 16/16, identical to the pre-merge baseline default-off A/B 22/22 byte-identical to stock origin/main compile 224 files, 0 syntax errors suite 21 failed / 3234 passed (from 35/3008 pre-merge) The 4b gate also did its job on this merge: it failed closed on six new resident-invalidation triggers and on a `benchmarking/` harness the exclusion list had missed (the -ing spelling was never added alongside bench/benchmarks). Both classified rather than waived.
Why: the registered 6-shard V1-M run died in a host reboot at ~hour 17 with ZERO results on disk —
run_harnessaccumulated results in memory and wrote the report only at run end. RUN-LOG discloses the loss; the run sheet's Amendment 2 corrects its wrong resume claim.What: per-question checkpoint jsonl appended+flushed after each question (side artifact — the final report bytes are unchanged, golden test untouched);
--resumeseeds aggregation from the checkpoint and skips completed questions; fail-closed handling (torn FINAL line truncated with warning + rerun of that question; mid-file corruption, wrong-question-set, and duplicate ids all raise); equivalence test proves a resumed run's final report is identical to an uninterrupted run on the same inputs.Suite: 73 passed, 1 skipped (bare exit-code gated). The V1-M flagship restart is gated on this merging.
Summary by CodeRabbit
New Features
Bug Fixes
Tests