Skip to content

fix(schemas): batch large journal units - #2971

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

Sinity merged 1 commit into
masterfrom
feature/fix/journal-sample-batches

Conversation

@Sinity

@Sinity Sinity commented Jul 17, 2026 •

Copy link
Copy Markdown
Owner

Summary

Batches sample insertion inside one schema observation unit so an unusually
large Codex transcript cannot create one multi-gigabyte private WAL
transaction.

Problem

Live Codex regeneration established that an individual SchemaUnit can carry
223,710 samples. The prior transaction repair committed between units, but only
after all samples in a unit had been inserted; that still allowed one giant
unit to exceed the intended journal transaction window.

Solution

Insert sample rows in bounded row/byte batches and account each completed batch
toward the existing private transaction budget. No sample, schema observation,
or generated output is dropped; incomplete journals remain private staging and
are removed on interruption.

Ref polylogue-1xc.14.1.1.

Verification

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

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of large observation journals by committing sample data in manageable batches during ingestion.
    • Reduced the risk of delayed writes and excessive memory usage when processing units with many large samples.
  • Tests

    • Added regression coverage confirming that large sample sets are committed incrementally before ingestion completes.

A Codex observation can contain hundreds of thousands of samples. Commit
inside such a unit in bounded sample-byte batches so one transcript cannot
turn the entire private WAL budget into one transaction.

Ref polylogue-1xc.14.1.1
@Sinity
Sinity merged commit 810037b into master Jul 17, 2026
1 check passed
@Sinity
Sinity deleted the feature/fix/journal-sample-batches branch July 17, 2026 04:38
@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3ed93b37-5679-4a10-8555-d8ac57c88b05

📥 Commits

Reviewing files that changed from the base of the PR and between 0d081e5 and 6dc70b6.

📒 Files selected for processing (2)
  • polylogue/schemas/generation/observation_journal.py
  • tests/unit/core/test_schema_observation_journal.py

📝 Walkthrough

Walkthrough

ObservationJournal now inserts samples incrementally using row-count and payload-size thresholds, records pending writes per batch, and preserves final cluster/profile accounting. A regression test verifies partial sample commits during ingestion of a large SchemaUnit.

Changes

Observation journal batching

Layer / File(s) Summary
Thresholded sample writes and regression coverage
polylogue/schemas/generation/observation_journal.py, tests/unit/core/test_schema_observation_journal.py
Sample JSON is buffered and flushed with executemany when row-count or byte thresholds are reached. Pending-write accounting is updated per batch, and the test verifies that some but not all samples are committed before unit ingestion finishes.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant SchemaUnit
  participant ObservationJournal
  participant SQLite
  SchemaUnit->>ObservationJournal: append_unit with schema_samples
  ObservationJournal->>ObservationJournal: buffer canonicalized sample JSON
  ObservationJournal->>SQLite: executemany sample batch
  SQLite-->>ObservationJournal: commit partial samples
  ObservationJournal->>ObservationJournal: record batch pending-write bytes
  ObservationJournal->>SQLite: finalize cluster and profile writes
Loading
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/journal-sample-batches

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 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