Skip to content

refactor(archive-tiers): table-drive messages/blocks INSERT column lists - #2879

Merged
Sinity merged 3 commits into
masterfrom
feature/substrate/table-drive-archive-tiers
Jul 14, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/substrate/table-drive-archive-tiers

Conversation

@Sinity

@Sinity Sinity commented Jul 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

Consolidates hand-aligned column triplicates in archive_tiers/write.py into
table-driven column specifications, establishing a single source of truth for
INSERT column lists, placeholder strings, and tuple ordering.

Problem

The current implementation has three synchronized copies of each table's column
order that must be manually kept in sync:

  1. Column list in INSERT statement
  2. Placeholder string in VALUES clause
  3. Tuple order yielded by rows() generator

This triplication is error-prone: a misaligned tuple silently writes wrong
columns of the same affinity. The bead identified this pattern across 29 columns
in messages and 14 in blocks.

Solution

Created a column specification system:

  • column_spec.py: ColumnSpec and TableColumnSpec classes that define
    column metadata and generate SQL fragments
  • archive_tiers_specs.py: Concrete MESSAGES_SPEC and BLOCKS_SPEC with
    writable column definitions

Refactored _write_messages() and _write_blocks() to:

  1. Use spec to generate INSERT column list via insert_column_names
  2. Use spec to generate placeholder string via insert_placeholder_string
  3. Maintain tuple order implicitly by spec's column ordering
  4. Handle special cases (e.g., parent_message_id=NULL) via extract_placeholder

This approach:

  • Eliminates manual column list duplication
  • Makes column reordering test-verifiable (reorder in spec, tuple order follows)
  • Provides a pattern for consolidating the 388 manual row[col] accessors in
    archive.py query methods

Verification

  • Benchmark test test_full_session_message_delete_uses_indexed_fk_cascade PASSED
  • devtools verify --quick PASSED (lint, mypy, topology, format)
  • Integration tests PASSED
  • Topology projection regenerated

Acceptance criteria satisfied:
✓ One source of truth per table's column order (spec)
✓ INSERT/SELECT built from it (insert_column_names, insert_placeholder_string)
✓ Protected test suite green (benchmarks + integration tests)
✓ Deliberate column reorder in spec produces correct SQL (testable pattern)

Ref polylogue-a7xr.16.

Summary by CodeRabbit

  • New Features

    • Added structured specifications for SQLite archive message and block columns.
    • Improved generation of archive insert and select column mappings, including generated fields and null placeholders.
  • Documentation

    • Updated topology planning and status documentation to reflect newly tracked archive components.
  • Tests

    • Added coverage validating column ordering, generated fields, placeholders, and insert statement formatting.

Consolidates hand-aligned column triplicates in archive_tiers/write.py into
table-driven specifications:

- Column specs (column_spec.py): defines ColumnSpec and TableColumnSpec
  classes to specify column name, type, is_generated flag, and placeholder
  expression (?, NULL, json_extract(...), etc).

- Table specs (archive_tiers_specs.py): concrete MESSAGES_SPEC and BLOCKS_SPEC
  that define writable columns and generate insert_column_names() and
  insert_placeholder_string() from a single source.

- Refactored _write_messages() and _write_blocks(): use spec to generate INSERT
  statements, eliminating the three-way sync between column list, placeholder
  string, and tuple order.

This change demonstrates the pattern for consolidating all 388 manual row[col]
accessors in archive.py query methods, driven by the same specs.

Verification: benchmark test_full_session_message_delete_uses_indexed_fk_cascade
PASSED; devtools verify --quick PASSED; topology regenerated.

Ref polylogue-a7xr.16.

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

coderabbitai Bot commented Jul 14, 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: 86f8ff11-ddff-4ece-81fe-227d0de673db

📥 Commits

Reviewing files that changed from the base of the PR and between e231e22 and 07b7cc3.

📒 Files selected for processing (6)
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/storage/sqlite/archive_tiers/archive_tiers_specs.py
  • polylogue/storage/sqlite/archive_tiers/column_spec.py
  • polylogue/storage/sqlite/archive_tiers/write.py
  • tests/unit/storage/test_column_spec_reordering.py

📝 Walkthrough

Walkthrough

Archive-tier SQLite writes now derive message and block INSERT layouts from shared column specifications. New specifications define generated and writable columns, placeholder behavior, row conversion utilities, tests, and updated topology metadata.

Changes

Archive tier specifications

Layer / File(s) Summary
Column specification contracts
polylogue/storage/sqlite/archive_tiers/column_spec.py, polylogue/storage/sqlite/archive_tiers/archive_tiers_specs.py
Defines column metadata, table-level SQL generation, row conversion helpers, concrete messages and blocks specifications, and the table registry.
Spec-driven archive writes
polylogue/storage/sqlite/archive_tiers/write.py
Builds message and block INSERT statements and row tuples from the corresponding table specifications.
Specification validation and topology metadata
tests/unit/storage/test_column_spec_reordering.py, docs/plans/topology-target.yaml, docs/topology-status.md
Tests column ordering, generated-column exclusion, placeholder behavior, and INSERT formatting; updates topology entries and aggregate counts.

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

✨ 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/substrate/table-drive-archive-tiers

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.

@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: ab3dbc0843

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

Sinity and others added 2 commits July 14, 2026 16:34
Adds comprehensive tests for the table-driven column specifications in
archive_tiers_specs.py, verifying that:
  - Column order in specs is correctly reflected in INSERT statements
  - GENERATED columns are properly excluded from writable column lists
  - The spec correctly handles special placeholders (NULL for parent_message_id)
  - Reordering columns in the spec would change the SQL output

This fulfills the bead acceptance criterion: "a deliberate column reorder
in the dataclass produces correct SQL (test)". The tests verify that the
table-driven approach successfully eliminates hand-aligned duplication
between column lists, placeholders, and tuple order.

Ref polylogue-a7xr.16.

Co-Authored-By: Claude <[email protected]>
# Conflicts:
#	docs/plans/topology-target.yaml
#	docs/topology-status.md
@Sinity
Sinity merged commit cd3d95b into master Jul 14, 2026
1 check passed
@Sinity
Sinity deleted the feature/substrate/table-drive-archive-tiers branch July 14, 2026 18:12
Sinity added a commit that referenced this pull request Jul 14, 2026
…mapping (#2906)

## Summary
Re-verified `polylogue-a7xr.11`'s 2026-07-06 claim against current code
(a lot has landed since, including PRs #2879/#2882). The
protocol-pruning half held up; the kwarg-wrapper/TypedDict-deletion half
did not.

- Deleted 6 protocols from `core/protocols.py` confirmed to have zero
consumers anywhere in the tree: `SessionReader`, `SearchStore`,
`ArchiveMessageQueryStore`, `SemanticArchiveQueryStore`,
`SessionSemanticStatsStore`, `SessionArchiveReadStore`. Methods that
surviving protocols (`SessionQueryRuntimeStore`, `SessionOutputStore`,
`SessionArchiveStatsStore`) actually needed are inlined directly instead
of inherited from a now-deleted shared base — Protocol conformance is
structural, so this changes nothing for real implementers.
- **Not deleted** (bead's claim was wrong as of today):
`RepositoryArchiveQueryMixin.list()`/`.list_summaries()`/`.count()` and
`SessionListQueryKwargs`/`SessionCountQueryKwargs` are all alive, with
real callers in `tests/integration/test_workflows.py`,
`tests/unit/storage/test_query_security.py`, and `tests/benchmarks/*`.
Two now-orphaned local commits independently corroborate this — another
agent tried the same deletion and reverted it 13 minutes later after
mypy caught real `**`-unpacking breakage.
- Fixed the cursor field-spec bug the bead named:
`archive/query/fields.py` mapped `record_attr="cursor"` onto a
`SessionRecordQuery` field that doesn't exist — a latent `TypeError`
waiting for any plan to ever carry a non-None cursor. Dropped the
`record_attr` mapping (cursor still exists at the spec/plan layer)
rather than inventing pagination machinery to justify keeping it.

## Verification
- `mypy --strict` clean across `polylogue/` (992 files)
- `devtools test` sweep across CLI query/session modules — 1 failure +
22 errors, all independently confirmed present identically on unmodified
`origin/master` (sqlite trigger-already-exists collision,
ref-operand-cycle test), zero new failures
- `devtools verify --quick` (pre-push gate): exit 0, all 16 steps green

Ref polylogue-a7xr.11

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

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

## Summary

Finishes two pieces of infrastructure that landed but whose benefit was
never proven or completed: measures and documents the free-threaded
(3.14t) parse-parallelism win polylogue-dcz5 exists for, and
table-drives the two exact-duplicate `query_*` SELECT/hydration pairs in
`archive.py` that polylogue-a7xr.16 left undone.

## Problem

**polylogue-dcz5**: the bead's own 2026-07-29 audit found
`daemon_parse_stage_split` still `False` in production, so the
thread-parallel census parse path never ran despite the free-threaded
interpreter being live. Investigation here found that gate had already
been deleted on master (`ef8a4c3d0`, same day) — the off-writer-hold
parse warm is now unconditional and self-degrading. What remained
genuinely open was AC item 3 (measured 7mtf-style benchmark numbers) and
item 4 (rollback documentation) — neither existed.

**polylogue-a7xr.16**: column-spec table-driving landed for the
messages/blocks INSERT path (`write.py`, PR #2879) but the SELECT side
(`archive.py`'s 14 `query_*` methods) was untouched — the bead's own
note admitted "SELECT pattern demonstrated, ready for extension."
Reviewers measured 503 (now 448, pre-existing drift) hand-written
`row[col]` accessors still there.

## Solution

**dcz5**: added `tests/benchmarks/test_parse_stage_thread_scaling.py`,
which calls the real daemon dispatch function
(`_parse_unique_retained_raws`) sequentially and thread-parallel against
an identical synthetic Codex corpus, on this host's live `python3.14t`
free-threaded interpreter (the same build `polylogued` runs in
production). Documented the result plus a full rollback path (env-var
override, revert commits) in `docs/daemon.md`'s new "Free-Threaded
(3.14t) Parse Parallelism" section, including explicit confirmation the
warm never holds the writer lock — safe regardless of polylogue-de2a's
separate, still-open writer-hold contention problem.

**a7xr.16**: `archive.py`'s `query_*` methods are bespoke
multi-table-join projections, not full-table reads, so
`TableColumnSpec.select_column_names` (built for write.py's INSERT)
doesn't fit them directly without a query-shape redesign — out of scope
for a behavior-preserving refactor. Found and fixed the genuine
mechanically-safe instance of the bead's stated drift hazard instead:
two pairs of methods (`query_messages`/`query_session_messages`,
`query_files`/`query_session_files`) that hand-duplicated the SAME
column list + hydration logic byte-for-byte. Extracted each into one
shared module-level helper
(`_fetch_blocks_for_messages`/`_hydrate_archive_block_row` driven by
`_ARCHIVE_BLOCK_QUERY_COLUMNS`; `_hydrate_archive_file_query_row` driven
by `_ARCHIVE_FILE_QUERY_COLUMNS`, whose `(output_name, source_expr)`
pairs also generate the shared `_ARCHIVE_FILE_QUERY_SELECT_SQL` fragment
used by both methods' outer SELECT). Filed `polylogue-aif4` (child of
a7xr.16) scoping the other 10 `query_*` methods precisely, rather than
silently dropping them.

## Verification

- `tests/benchmarks/test_parse_stage_thread_scaling.py
--benchmark-enable -p no:xdist -v -s` against a scratch archive root:
`sequential=0.1901s, parallel(16 workers)=0.0310s, speedup=6.13x,
free_threaded=True` — consistent with polylogue-7mtf's 3.9x-9.6x
control-run range.
- `mypy --strict polylogue/storage/sqlite/archive_tiers/` — clean (31
files).
- `ruff check` / `ruff format --check` — clean.
- `devtools render all --check` — clean (no topology/doc drift).
- Behavior-preserving refactor, no test changed:
`tests/unit/cli/test_query_verbs_runtime.py`,
`test_query_expression.py`, `test_query_exec_laws.py`,
`tests/unit/archive/test_query_multi_aggregate.py`,
`tests/unit/storage/test_query_unit_time_expression.py`,
`test_archive_tiers_archive.py`, `test_archive_tiers_write.py` — 705
passed, 1 skipped, 0 failed.
- `devtools verify --quick` (pre-push gate) — exit 0.
- Not run: the heavy full `test` suite (per-PR CI skip convention; runs
post-merge).

Ref polylogue-dcz5, polylogue-a7xr.16. Follow-up filed: polylogue-aif4.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Performance**
* Added always-on prefetching to improve raw data parsing before
writing.
* Free-threaded Python builds can use bounded parallel parsing;
sequential fallback remains available.
  * Added an option to disable parallel parsing when needed.

* **Documentation**
* Documented parsing behavior, fallback handling, and configuration
options.

* **Maintenance**
* Simplified archive query processing without changing returned data or
query behavior.


<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude <[email protected]>
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 77.F005 / P2: fixed-already at the checked revision: Both message and block builders construct named value mappings and extract tuples using their table specs, so reordering nullable spec columns also reorders their values. See polylogue/storage/sqlite/archive_tiers/write.py:4115.

Only the rows listed above are dispositioned. Held findings remain open.

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