Skip to content

fix(sources): require structural evidence for codex CONTINUATION lineage - #3484

Merged
Sinity merged 1 commit into
masterfrom
fix/sources/codex-continuation-structural-evidence
Jul 31, 2026
Merged

Sinity merged 1 commit into
masterfrom
fix/sources/codex-continuation-structural-evidence

Conversation

@Sinity

@Sinity Sinity commented Jul 31, 2026

Copy link
Copy Markdown
Owner

Summary

The Codex parser's legacy lineage fallback (used when no forked_from_id marker is present) classified a session as BranchType.CONTINUATION from a bare count of session_meta records — any second embedded session_meta was assumed to be the parent, regardless of what it actually was.

Problem

polylogue/sources/parsers/codex.py:2512-2514 (pre-fix):

elif len(session_metas_seen) > 1:
    parent_id = session_metas_seen[1]
    branch_type = BranchType.CONTINUATION

This is the same proxy-as-truth mechanism already fixed for the adjacent FORK/RESUME (forked_from_id) path (comment at the surrounding lines documents that discipline), left unaddressed for the count-based CONTINUATION fallback. A fabricated lineage edge is worse than a missing one — session_links composes transcripts from these edges.

I inspected real multi-meta Codex rollout files (~/.codex/sessions/**/*.jsonl, files with 2-3 distinct session_meta records) to find what a genuine resume's replayed parent header actually looks like structurally. Two facts held consistently: the replayed parent header's timestamp always precedes the new session's own start time (by seconds-to-minutes), and it reports the same cwd/git repository_url as the child, because the resume continues in the same working tree. A bare count proves neither.

Solution

Added _has_continuation_evidence() to polylogue/sources/parsers/codex.py, requiring:

  1. the second session_meta's timestamp does not postdate the first's, and
  2. the two metas share a matching cwd or a matching git repository_url.

The legacy fallback now calls this before assigning CONTINUATION. When the evidence is absent, both parent_id and branch_type stay unclassified (None), matching the pattern already applied to forked_from_id. Captured the second meta's cwd/git/timestamp with new local variables (second_meta_timestamp_pair, second_meta_cwd, second_meta_repo_url) independent of the existing session_git/session_timestamp bookkeeping, which intentionally tracks only the first (child) meta.

Anti-vacuity: the new negative tests (test_second_session_meta_without_structural_evidence_stays_unclassified in tests/unit/sources/test_parsers_codex.py, test_second_session_meta_without_structural_evidence_is_unclassified in tests/unit/sources/test_codex_event_stream_contract.py) exercise polylogue.sources.parsers.codex.parse/parse_stream end to end. Reverting _has_continuation_evidence's call site back to the old elif len(session_metas_seen) > 1: heuristic (dropping the evidence check) makes both fail: they'd assert branch_type is None / parent_session_provider_id is None against a payload the old code would have classified as CONTINUATION with an unrelated parent id.

Verification

  • python -m devtools test tests/unit/sources/test_parsers_codex.py tests/unit/sources/test_codex_event_stream_contract.py tests/unit/sources/test_parsers_codex_catalog.py → 129 passed
  • python -m mypy polylogue/sources/parsers/codex.py → Success: no issues found in 1 source file
  • python -m devtools verify --quick → exit_code: 0 (ruff format/check, mypy, render-all-check, topology, layering, closure-matrix, schema/manifest/lab policy checks)

Scope note

Confined to polylogue/sources/parsers/codex.py and its two direct test files, per the conflict note in polylogue-psz6: the classification-gate work in sources/dispatch/base_support is a separate lane's territory.

Ref polylogue-psz6

Problem: the Codex parser's legacy (no forked_from_id) lineage fallback
classified any session with a second embedded session_meta record as a
CONTINUATION of that meta's id, purely from the record count. Real
multi-meta rollout files show two structural facts about a genuine
resume's replayed parent header instead: its timestamp precedes the new
session's own start time, and it reports the same cwd/git remote (the
resume continues in the same working tree). Two structurally unrelated
session_meta records concatenated in one payload would satisfy the old
count check without satisfying either fact, fabricating a lineage edge
that session_links composes transcripts from.

Solution: add `_has_continuation_evidence()` in
polylogue/sources/parsers/codex.py, which requires the second meta's
timestamp to not postdate the first's plus a matching cwd or git
repository_url. The legacy fallback now calls this before assigning
CONTINUATION; when the evidence is absent, both parent_id and
branch_type stay unclassified, matching the discipline already applied
to the adjacent FORK/RESUME (forked_from_id) path. Captured the second
meta's cwd/git/timestamp independently of the existing session_git/
session_timestamp bookkeeping, which track only the first (child) meta.

Verified the timestamp/cwd/git pattern against real multi-meta Codex
rollout files on disk (`~/.codex/sessions/**/*.jsonl`) before writing
the check.

Verification:
- python -m devtools test tests/unit/sources/test_parsers_codex.py
  tests/unit/sources/test_codex_event_stream_contract.py
  tests/unit/sources/test_parsers_codex_catalog.py -> 129 passed
- python -m mypy polylogue/sources/parsers/codex.py -> no issues
- python -m devtools verify --quick -> exit 0 (format, lint, mypy,
  render-all-check, layering, schema/topology/manifest lab checks)

Ref polylogue-psz6

Co-Authored-By: Claude <[email protected]>
@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, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 59 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 99e49828-4967-4919-8431-d01d26923646

📥 Commits

Reviewing files that changed from the base of the PR and between c46e48c and 89182b1.

📒 Files selected for processing (3)
  • polylogue/sources/parsers/codex.py
  • tests/unit/sources/test_codex_event_stream_contract.py
  • tests/unit/sources/test_parsers_codex.py

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Sinity
Sinity merged commit 0d27e3d into master Jul 31, 2026
3 checks passed
@Sinity
Sinity deleted the fix/sources/codex-continuation-structural-evidence branch July 31, 2026 22:08
Sinity added a commit that referenced this pull request Jul 31, 2026
Sinity added a commit that referenced this pull request Jul 31, 2026
…3494)

## Summary

Two beads, one branch: (1) a P1 correctness-of-contract bug fix — a
resumable
rebuild pass's deadline is now checked *between* REPLAY-phase cohorts,
not
only after the whole page's replay call returns — and (2) the small
remaining
slice of a P2 observability bead, a durable "selection phase" timing on
every
rebuild receipt.

## Problem

**polylogue-uhgm** (P1): live recovery evidence — operation `3f8fa7b0`
configured `pass_deadline_ms=300000` (5 minutes), yet 100-row pages ran
roughly 8-9 minutes, because `rebuild_index_from_source`
(`maintenance/rebuild_index.py`) checked elapsed time only *after*
`replay_source(...)` — the whole page's census + every cohort +
planner-stats
refresh — returned. A page can also expand into a much larger authority
cohort, making the overshoot unbounded in the worst case. The advertised
bounded-pass contract was not enforced at the work boundary.

**polylogue-6mvg** (P2, remaining slice): a live full index rebuild
spent
~86s of one CPU core selecting which raws to replay before the inactive
generation held a single session, and nothing durable recorded where
that
time went. Most of this bead's original scope (planner stats #3141,
byte-skip #3146, batched commits #3147, pool floor #3149, dedup #3151)
had
already shipped via sibling beads; the bead's own notes call out durable
phase-timing telemetry — specifically a selection-phase breakdown — as
the
one still-unowned piece.

## Solution

- `polylogue/sources/revision_backfill.py`:
`backfill_historical_revision_evidence`
gains an optional `deadline_check: Callable[[], None] | None` parameter,
  called at the top of every REPLAY-phase cohort iteration (both the
byte-cohort and membership-cohort loops) — between cohorts, not only
after
the whole call returns. New `RebuildDeadlineExceededError` is the
expected
  interrupt signal.
- `polylogue/maintenance/replay.py`: threads `deadline_check` through
  unchanged to `backfill_historical_revision_evidence`.
- `polylogue/maintenance/rebuild_index.py`:
- Builds a `_check_pass_deadline` closure from the resumable
transaction's
`pass_deadline_ms`, wired only when a durable transaction exists (never
for non-resumable `--raw-id`/`--only-missing`/`--max-blob-mb`
selections,
    matching existing validation).
- Catches `RebuildDeadlineExceededError` around the `replay_source()`
call.
    On interrupt it deliberately does **not** advance the transaction's
cursor/processed counters — the next pass re-derives from the exact same
    source-order position, safe by the existing content-hash idempotency
invariant (re-applying an already-committed cohort is a no-op upsert,
never a duplicate) and consistent with the crash-recovery contract an
    open replay batch already has.
- The deferred receipt's `replay` dict is zero-shaped like a normal
replay
    dict (not a bare marker), so every existing consumer that indexes
replay-dict keys unconditionally (the daemon-mode CLI text formatter,
the
    daemon HTTP route's raw `receipt.to_dict()` response) keeps working.
- `RebuildPassCost.selection_s` (polylogue-6mvg) extends the *existing*
timings vocabulary — the same `RebuildPassCost`/`timings_s` shape every
    other phase (`parse_s`/`apply_s`, the `terminal.*` stages from
    polylogue-o56w) already uses — rather than inventing a parallel one.
    Measured around `next_raw_page` (resumable path) and
    `select_rebuild_raw_ids` (one-shot path), threaded into all three
    receipt-building call sites (deadline-interrupt, deferred/paused
    post-hoc, final materialized).

**Alternatives rejected:** proactive page-sizing against a throughput
estimate (checks only *before* a page starts, so still misses a
mid-page-expanding cohort — the exact worst case the bead names) and
per-raw interruption inside `apply_raw_revision_replay` itself (would
interrupt mid-transaction-write, risking corruption of the
owned-inactive-
generation state). Both were flagged and deliberately deferred in the
bead's own prior investigation as too risky for the intended scope.

## Conflict avoidance note for the merge conductor

`polylogue/sources/revision_backfill.py` is flagged as owned by another
live
lane. This PR's addition there is the smallest possible: one new
exception
class, one new optional parameter, and two `if deadline_check is not
None:
deadline_check()` call sites at the top of the two existing cohort loops
—
no other line touched. The branch was rebased onto current `master`
(`90d4df67e`, which includes the sibling lane's `polylogue-5q2u`
lineage-order
replay change, `_lineage_aware_replay_order`); the rebase conflict was
exactly the loop header line and was resolved by keeping the new
`ordered_logical_keys` iteration and re-adding the `deadline_check()`
call —
verified with a fresh test run post-rebase.

## Acceptance-criteria matrix

**polylogue-uhgm:**
- "A transaction with a short pass deadline stops before starting work
that
  would exceed its remaining budget, commits a valid cursor, and reports
deadline deferral." — **Satisfied.**
`test_rebuild_index_deadline_stops_mid_page_and_resumes_without_omission_or_duplication`.
- "Restarting resumes exactly at the next source-order raw/cohort with
no
duplicates or omissions." — **Satisfied** (by construction: the cursor
is
never advanced on interrupt, and resumption re-derives from the
identical
keyset position; idempotent re-application makes any redone cohort
safe).
Proven end-to-end by the same test (interrupted pass → resume → exact
final
  session count).
- "A deliberately slow/expanded cohort proves the deadline is checked
inside
production replay work rather than only after the outer call returns." —
**Satisfied.**
`test_deadline_check_invoked_between_replay_cohorts_not_only_after_return`
proves the interrupt fires after exactly one cohort durably commits (not
zero, not all three) at the direct
`backfill_historical_revision_evidence`
  boundary.
- "Final terminal readiness checks remain exact and either have their
own
bounded receipt or are explicitly separately scheduled." —
**Unchanged**:
no terminal-stage code was touched; `terminal.*` timings
(polylogue-o56w)
  remain as before.

**polylogue-6mvg** (remaining slice only — full bead AC already
satisfied by
sibling beads per its own 2026-07-19/27 notes):
- Durable selection-phase timing receipt — **Satisfied.**
  `RebuildPassCost.selection_s` / `terminal_timings_s["selection_s"]`,
  present on every receipt shape (deferred, paused, replayed).
- Cohort/parse/write/insight phase timings — **Already delivered** by
prior
work (`stage_timings_s` from `revision_backfill.py`, `parse_s`/`apply_s`
  split, `terminal.*` stages) — not re-touched here.
- Daemon catch-up shares the improvement — **Satisfied by
construction**:
`daemon/bulk_rebuild.py`'s `run_daemon_bulk_rebuild_pass` returns the
exact
same `RebuildIndexReceipt` from the same
`rebuild_index_from_source_sync`
  engine, so both the deadline fix and the selection-phase timing apply
  automatically with zero daemon-side changes needed.

## Anti-vacuity

- Deadline fix: production caller is `rebuild_index_from_source_sync`
(the
real offline/daemon rebuild engine, no reimplementation). The mutation
that
makes
`test_deadline_check_invoked_between_replay_cohorts_not_only_after_return`
fail is moving the `deadline_check()` calls out of the cohort loops back
to
a single call after `backfill_historical_revision_evidence` returns (the
  pre-fix bug shape) — the mock would then never be called before the
  function's own natural completion. The mutation that makes

`test_rebuild_index_deadline_stops_mid_page_and_resumes_without_omission_or_duplication`
fail is either reverting to the post-hoc-only check (the fake clock
would
  never interrupt anything mid-replay, so the first pass would report
`status="replayed"` instead of `"deferred"`) or advancing the
transaction's
cursor on interrupt (the resumed pass would then skip or duplicate a
raw,
  and the final session count would not equal 3).
- Phase timing: production caller is the same
`rebuild_index_from_source_sync`.
The mutation that makes `test_rebuild_index_phase_timing.py`'s two tests
  fail is reverting `selection_elapsed_s`'s measurement or its
`selection_s=selection_elapsed_s` threading — the `"selection_s"` key
would
then be absent from `receipt.timings_s` (a dict-key assertion failure,
not
  merely a zero value).

## Verification

```
python -m devtools test tests/unit/maintenance/test_rebuild_index_deadline.py \
  tests/unit/maintenance/test_rebuild_index_phase_timing.py \
  tests/unit/daemon/test_bulk_rebuild_ownership.py \
  tests/unit/cli/test_archive_maintenance_cli.py \
  tests/unit/daemon/test_route_contracts.py \
  tests/unit/maintenance/test_rebuild_index_bulk_build.py \
  tests/unit/maintenance/test_rebuild_index_ownership.py \
  tests/unit/maintenance/test_rebuild_index_selection.py \
  tests/unit/maintenance/test_rebuild_parse_apply_split.py \
  tests/unit/storage/test_index_generation.py
# 212 passed
python -m devtools verify --quick
# exit_code: 0, all 18 steps ok
```

**Known pre-existing failure, unrelated to this branch** — filed as
`polylogue-s0ug`:

`tests/unit/storage/test_incremental_rebuild_equivalence.py::test_incremental_restart_and_fresh_generation_rebuild_are_equivalent`
fails deterministically on current `origin/master` (`90d4df67e`) in
isolation,
introduced by `0d27e3da7` (#3484, tightened Codex CONTINUATION lineage
evidence) landing after this branch was cut — the test's hand-built
fixture
predates that tightening. `git diff origin/master...HEAD` for this
branch
touches neither `codex.py`, `revision_backfill.py`'s classification
logic,
nor that test file, confirming it is not caused by this change.

Not run: `devtools verify` (full testmon suite) — the coordinator
directed a
synchronous quick-gate + focused-test path instead of the backgrounded
testmon seed, since a fresh worktree has no testmon seed to run the
default
affected-selection path against.

Ref polylogue-uhgm
Ref polylogue-6mvg

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

---------

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 31, 2026
…evidence (#3498)

## Summary

Fixes the master regression
`test_incremental_restart_and_fresh_generation_rebuild_are_equivalent`,
which fails deterministically after 0d27e3d (#3484, "require
structural evidence for codex CONTINUATION lineage"). The fixture, not
the parser rule, was wrong — verdict below.

## Problem

0d27e3d replaced a bare "second `session_meta` count" heuristic in the
Codex parser's legacy (no `forked_from_id`) CONTINUATION fallback with
`_has_continuation_evidence()`, requiring (1) the candidate parent's
replayed header timestamp does not postdate the child's own start time,
and (2) the two `session_meta` records share a matching `cwd` or git
`repository_url`.


`tests/unit/storage/test_incremental_rebuild_equivalence.py::_codex_session`
builds a synthetic Codex payload with two `session_meta` records that
only set `id` and `timestamp` — no `cwd`, no `git`. After 0d27e3d this
no longer satisfies `_has_continuation_evidence` (timestamp precedence
alone is not sufficient; cwd/git must also match), so the parser
correctly leaves the fixture's lineage unclassified, and the equivalence
test's `session_links` assertion (expecting a
`('codex-session:lineage-parent', 'continuation')` edge) fails.

## (a) vs (b) verdict: (a) — the fixture was stale, the rule is correct

I sampled real multi-`session_meta` Codex rollouts from
`~/.codex/sessions/**/*.jsonl` (3,213 files total, 494 with ≥2 distinct
`session_meta` records) and compared the first two distinct
`session_meta` payloads in each:

- **490/494 (99.2%)** share a matching `cwd` between the first and
second `session_meta`.
- **0/494** match on git `repository_url` alone without also matching
`cwd` (git match is a strict subset of cwd match in this sample).
- **494/494 (100%)** have the second meta's timestamp `<=` the first's
(true replay-of-parent-header ordering).
- Only 4/494 files have neither cwd nor git-repo match — inspected
manually, these are genuinely unrelated `session_meta` pairs from
different repos/directories, i.e. exactly the shape
`_has_continuation_evidence` is designed to reject.

This confirms 0d27e3d's premise: real Codex continuations
overwhelmingly carry the structural evidence the tightened rule
requires, and the 4 non-matching cases are legitimately *not*
continuations. The rule is correct; the pre-existing test fixture simply
predates it and never populated `cwd`/`git` on its synthetic
`session_meta` records, so it can't produce the evidence a real
continuation would.

## Solution

`tests/unit/storage/test_incremental_rebuild_equivalence.py`:
`_codex_session` now sets a shared `cwd`
(`/realm/project/lineage-fixture`) on both the child's own
`session_meta` and the parent's replayed `session_meta`, mirroring what
real continuation rollouts structurally carry. Left the existing
timestamp ordering (parent timestamp precedes child) untouched — it
already matched the requirement.

No changes to `polylogue/sources/parsers/codex.py` or
`_has_continuation_evidence` itself — the classification rule from #3484
is unchanged.

## Verification

- `python -m devtools test
tests/unit/storage/test_incremental_rebuild_equivalence.py
tests/unit/sources/test_parsers_codex.py
tests/unit/sources/test_codex_event_stream_contract.py` → `121 passed`
(includes the target equivalence test now green, plus #3484's negative
case
`test_second_session_meta_without_structural_evidence_stays_unclassified`
/ `..._is_unclassified` still passing unchanged).
- `python -m devtools verify --quick` → `exit_code: 0` (format, lint,
mypy, render-all-check, layering, schema/manifest/lab policy checks).

**Anti-vacuity**: the production dependency exercised is
`polylogue.sources.parsers.codex._has_continuation_evidence` via
`parse()`/`parse_stream()` — reverting the fixture change back to
session_metas with no `cwd`/`git` (i.e. restoring the pre-PR state)
reproduces the original failure: `_has_continuation_evidence` returns
`False`, `session_links` gets no `('codex-session:lineage-parent',
'continuation')` edge, and the equivalence assertion at the affected
line fails again.

Ref polylogue-s0ug
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