Skip to content

fix(schemas): bound journal replay transactions - #2968

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/schema-journal-replay
Jul 17, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/schema-journal-replay

Conversation

@Sinity

@Sinity Sinity commented Jul 17, 2026

Copy link
Copy Markdown
Owner

Summary

Bounds private observation-journal transactions and makes membership replay
apply selective unit filters before reading samples.

Problem

A live full-corpus Codex regeneration accumulated a 41.7 GiB SQLite WAL because
journal ingest committed only at close. After ingest, package/schema replay
continued at roughly 1.48 GiB of physical reads per 30 seconds. Its SQL forced
samples to be the outer relation, so package/profile predicates could not
narrow work before sample replay.

Solution

  • Commit bounded private journal batches and explicitly flush after ingest,
    before any replay phase. Generated artifacts are still published only after
    successful generation; this changes spool durability, not output semantics.
  • Start membership replay at filtered units, then join samples; retain
    indexes aligned with profile/package and artifact filters.
  • Add behavioral coverage for committed private replay visibility and an
    EXPLAIN QUERY PLAN contract proving a selective package lookup uses units
    then the per-unit samples primary key.

Ref polylogue-1xc.14.1.1.

Verification

  • devtools test tests/unit/core/test_schema_observation_journal.py tests/unit/core/test_schema_generation.py — 46 passed.
  • devtools verify --quick — all 16 checks passed.
  • Pre-push quick baseline — all checks passed.

The full-corpus observation journal held its entire ingest in one SQLite
transaction, leaving a multi-gigabyte WAL for later replay. Membership replay
also forced samples to be scanned before selective package filters.

Commit private journal batches and flush before replay; start membership joins
from filtered units so SQLite can use package/profile indexes before samples.

Ref polylogue-1xc.14.1.1
@coderabbitai

coderabbitai Bot commented Jul 17, 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: 25 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

Run ID: 50a26cb6-6cbf-49bc-8ba0-a81e98baad97

📥 Commits

Reviewing files that changed from the base of the PR and between 9ddfc8d and d4cfa35.

📒 Files selected for processing (3)
  • polylogue/schemas/generation/cluster_collection.py
  • polylogue/schemas/generation/observation_journal.py
  • tests/unit/core/test_schema_observation_journal.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/schema-journal-replay

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 067c87e into master Jul 17, 2026
2 checks passed
@Sinity
Sinity deleted the feature/fix/schema-journal-replay branch July 17, 2026 03:06

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d4cfa3548b

ℹ️ 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".

# The following phases replay the journal repeatedly. Commit its final
# ingest batch first so reads do not repeatedly traverse one enormous
# writer WAL instead of the checkpointable journal database.
journal.flush()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Commit the full-corpus assignment phases before replay

On full-corpus generations, this flush only ends the ingest transaction; the subsequent apply_profile_summary_families_to_units, normalize_profile_families, and assign_canonical_package_families calls update the full units relation without invoking _record_pending_write or another flush(). Those updates therefore form one transaction that remains open through package/schema replay until close(), so its WAL cannot be checkpointed and can again grow with corpus size—the exact failure this change is intended to prevent.

Useful? React with 👍 / 👎.

Sinity added a commit that referenced this pull request Jul 27, 2026
… equivalence (#3298)

## Summary

Adds the two production-route tests needed to close the remaining proof gap on polylogue-1xc.14.1.1 ("Make schema inference replayable and memory-bounded"): cancellation equivalence for the real `generate_provider_schema` entrypoint, and shuffled-input-order equivalence for the real `_build_provider_bundle` pipeline. Both run against synthetic/demo data only.

## Problem

polylogue-1xc.14.1.1 landed heavy hardening for the `ObservationJournal` full-corpus pipeline (#2968, #2971, #2973: bounded batch commits, selective-membership replay, Hermes terminal-ledger accounting) with a 1x/10x memory-bound proof already in place. Two AC items were still unproven going into this pass:

- AC #2/#6 ("cancellation"): `grep -rn cancel polylogue/schemas/generation/observation_journal.py polylogue/schemas/generation/provider_bundle.py` returns zero hits. The existing tests (`test_journal_cleanup_runs_for_sigterm`, `test_journal_cleanup_runs_for_real_terminated_process`) only prove that a raw, low-level `ObservationJournal.append_unit` call cleans up on SIGTERM — they never exercise the real `generate_provider_schema` entrypoint, and none of them prove a killed-then-restarted run produces the *same output* as an uninterrupted run (the actual "equivalence" claim in the bead's own notes: "cancellation proof" listed as remaining scope).
- AC #5 ("shuffled input order produces the same schemas, package assignments, profiles, and identities"): `grep -rl shuffle tests/unit/` returns nothing anywhere under the schema test tree. This clause was simply untested.

## Solution

- `tests/infra/schema_generation_cancellation_probe.py` (new): a subprocess target that writes a small deterministic synthetic ChatGPT archive once (idempotent across repeated invocations against the same `--archive-root`, so it can be reused for the reference and restarted runs without re-seeding), then calls the real `generate_provider_schema`. With `--pause-after-observe` it installs a `progress_callback` that prints `PAUSED` right after the `observe_and_cluster` phase starts and sleeps, giving the parent a deterministic, non-flaky window to send SIGTERM mid-run.
- `tests/unit/core/test_schema_observation_journal.py`:
  - `test_generation_cancellation_restarts_from_scratch_and_matches_uninterrupted_run`: runs the probe to completion once (reference), then runs it again with `--pause-after-observe`, SIGTERMs it once `PAUSED` is observed, asserts the journal directory is empty afterward (same contract as the existing terminated-process test, now through the *real* generation entrypoint), then reruns to completion and asserts the resulting schema/sample_count/default_version are identical to the reference run. This empirically proves `devtools/schema_generate.py`'s own resume-receipt claim ("the private observation journal is intentionally removed after interruption" / `restart_from_acquisition`) actually holds for real generation, not just for a synthetic `ObservationJournal.append_unit` call.
  - `test_shuffled_sample_order_yields_identical_schema_and_package_assignment`: feeds an identical `SchemaUnit` multiset through the real `_build_provider_bundle` in two different orders, using the same `iter_schema_units` monkeypatch technique already established by `test_build_provider_bundle_captures_element_windows_and_bundle_scopes` in `test_schema_generation.py`. Asserts schema content (minus the wall-clock `x-polylogue-generated-at` field), package identity (`anchor_profile_family_id`, `profile_family_ids`, `sample_count`, `bundle_scope_count`, `first_seen`/`last_seen`), catalog version selection, and cluster-manifest identities (`exact_structure_ids`, `bundle_scope_count`) are all order-invariant.

### Not addressed in this PR

AC #5 also contains a separate clause: "Small known-answer provider bundles are byte/content equivalent to the reference algorithm except for newly declared profile metadata." I looked for what "the reference algorithm" refers to and could not find an unambiguous, non-fabricated interpretation: `generate_schema_from_samples` (the older genson-based helper) uses a structurally different shape-inference algorithm than `_generate_cluster_schema` (the production path's custom `observed_structure_schema`/`merge_observed_structure_schemas`), so comparing them would not be a meaningful equivalence proof — it would just assert two different algorithms disagree. The other candidate reading (the bead's own description mentions `list(iter_schema_units(...))` as the naive/eager alternative to the journal-backed streaming path) would require building a full parallel non-journal reference pipeline for cluster/package/catalog assembly purely for this test — a nontrivial, test-only duplicate implementation that risks becoming exactly the kind of toy replica the project's testing conventions reject. I left this alone rather than fabricate a shaky test; it's called out explicitly in the `bd update` note on polylogue-1xc.14.1.1 (kept open, not closed, because of this gap).

## Verification

```
devtools test tests/unit/core/test_schema_observation_journal.py tests/infra/schema_generation_cancellation_probe.py
# 17 passed

mypy polylogue
# Success: no issues found in 1078 source files

ruff check tests/unit/core/test_schema_observation_journal.py tests/infra/schema_generation_cancellation_probe.py
ruff format --check tests/unit/core/test_schema_observation_journal.py tests/infra/schema_generation_cancellation_probe.py
# All checks passed! / 2 files already formatted

devtools render all --check
# OK: site sources render and generated local links resolve. (test-only files, no topology drift)
```

`devtools test tests/unit/core/test_schema_generation.py` shows 6 pre-existing `sqlite3.OperationalError: database is locked` setup errors under `-n 2` xdist — reproduced identically on an unmodified checkout of this file before any of my changes, so it is pre-existing environment flakiness unrelated to this diff (not caused or fixed here).

The pre-push `devtools verify --quick` gate (format + lint + mypy + render-all-check) ran automatically on push and passed (exit_code 0).

Ref polylogue-1xc.14.1.1
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