Skip to content

feat(assertions): export user-tier assertions (#1883) - #2098

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/assertion-user-export-1883
Jun 18, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/assertion-user-export-1883

Conversation

@Sinity

@Sinity Sinity commented Jun 18, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds a durable assertion export surface for user.db, moves split-archive learning-correction storage onto assertion rows, and fixes the verification harness issues exposed while proving the broad seed run.

Problem

#1883 still had a backup/export/reset gap: assertions are irreplaceable user-tier state, but there was no direct export surface that included inactive/candidate/deleted rows. The split archive had also removed the old correction table while the async feedback storage path could still try to use it. During broad verification, the seed run exposed unrelated harness fragility: progress writes could race in parallel tests, xdist basetemp cleanup could interrupt report flush, and the memory-budget probe could report parent RSS larger than total tree RSS for very short commands.

Solution

  • Add ops maintenance assertion-export with JSONL/JSON output, --out, --kind, --status, and non-negative --limit filters.
  • Add list_assertions_for_export(...) and assertion_envelope_to_payload(...) over the typed assertion envelope so export output is deterministic and includes all statuses by default.
  • Store archive-root learning corrections in user_tier.assertions when split user.db is present, and tombstone correction assertions on delete/clear.
  • Fix assertion-backed blackboard note decoding for rows whose key is absent but target_ref carries the note id.
  • Update route/status snapshots for list_assertion_claims and current CLI command inventory.
  • Harden verify/test harness behavior: unique pytest progress temp files, no xdist basetemp deletion during session-finish teardown, and process-tree RSS never below parent RSS.

Verification

  • devtools test focused assertion/export/user-state/harness node set: 29 passed.
  • devtools test broad-run regression nodes: 7 passed.
  • ruff check and mypy --strict over changed files: passed.
  • devtools verify --quick: exit_code: 0.
  • devtools verify --seed-testmon --skip-slow: pytest seed completed with 11280 passed, 1 xfailed; the enclosing first seed command failed only because tests/unit/test_pytest_temp_policy.py needed formatting, then formatting and quick gate passed.
  • devtools verify: exit_code: 0, affected pytest 7 passed.

Ref #1883

Summary by CodeRabbit

  • New Features

    • Added maintenance assertion-export CLI command to export durable assertions from the archive in JSON or JSONL formats with optional filtering by kind and status
    • Feedback corrections now use assertions-based persistence for improved durability and consistency
    • Archive status reporting includes assertion claims routing information
  • Documentation

    • Updated scenario projection catalog with new exercise projections

github-actions Bot pushed a commit that referenced this pull request Jun 18, 2026
@coderabbitai

coderabbitai Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

More reviews will be available in 44 minutes and 47 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

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

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

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, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: b1a70a10-550a-47d9-a70d-dfecdb3c406e

📥 Commits

Reviewing files that changed from the base of the PR and between f6c6c91 and dd48264.

📒 Files selected for processing (24)
  • devtools/query_memory_budget.py
  • devtools/verify.py
  • docs/test-quality-workflows.md
  • polylogue/cli/commands/maintenance.py
  • polylogue/cli/commands/status.py
  • polylogue/storage/insights/feedback/__init__.py
  • polylogue/storage/sqlite/archive_tiers/user_write.py
  • tests/baselines/showcase/help-ops-maintenance-assertion-export.txt
  • tests/baselines/showcase/help-ops-maintenance.txt
  • tests/conftest.py
  • tests/unit/cli/__snapshots__/test_help_snapshots.ambr
  • tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr
  • tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr
  • tests/unit/cli/test_archive_maintenance_cli.py
  • tests/unit/cli/test_click_app.py
  • tests/unit/cli/test_diagnose_and_error_discipline.py
  • tests/unit/cli/test_query_exec_laws.py
  • tests/unit/daemon/test_daemon_cli.py
  • tests/unit/daemon/test_web_reader.py
  • tests/unit/insights/test_feedback.py
  • tests/unit/sources/test_live_batch_support.py
  • tests/unit/storage/test_archive_tiers_assertions.py
  • tests/unit/storage/test_no_string_interpolated_sql.py
  • tests/unit/test_pytest_temp_policy.py
📝 Walkthrough

Walkthrough

This PR introduces a new ops maintenance assertion-export CLI command that queries user.db assertion rows with optional kind/status/limit filtering and outputs JSON or JSONL. The feedback/correction archive storage is migrated from a legacy corrections table to soft-delete semantics on user_tier.assertions. Supporting storage helpers (list_assertions_for_export, assertion_envelope_to_payload) are added. Separately, archive query response fields move from flat to nested shapes, devtools/verify.py gets pytest count and temp-file fixes, and the conftest.py xdist cleanup gate gains a numprocesses check.

Changes

Assertion Export Feature & Feedback Storage Migration

Layer / File(s) Summary
New assertion export helpers in user_write.py
polylogue/storage/sqlite/archive_tiers/user_write.py
Adds assertion_envelope_to_payload() and list_assertions_for_export() (with kind/status/limit filtering, deterministic ordering); fixes _blackboard_envelope_from_assertion() note_id fallback to use target_ref; both functions added to __all__.
Feedback/correction storage migrated to user_tier.assertions
polylogue/storage/insights/feedback/__init__.py
upsert_correction, list_corrections, delete_correction, and clear_corrections archive paths rewritten to use user_tier.assertions with a {payload, note} JSON wrapper; deletes become soft deletes via status='deleted'; adds _attached_table_exists helper; capability detection now requires user_tier.assertions presence.
maintenance assertion-export CLI command and status route
polylogue/cli/commands/maintenance.py, polylogue/cli/commands/status.py
Adds assertion_export_command click command with format/path/kinds/statuses/limit options and a read-only SQLite helper _read_assertion_export_rows(); registers list_assertion_claims on the user tier in _ARCHIVE_FACADE_ROUTES; exports assertion_export_command.
Storage and CLI tests for assertion export
tests/unit/storage/test_archive_tiers_assertions.py, tests/unit/cli/test_archive_maintenance_cli.py, tests/unit/storage/test_no_string_interpolated_sql.py
Adds test_list_assertions_for_export_covers_all_kinds_and_statuses covering filter/pagination/payload shape; two end-to-end CLI tests seeded from _seed_assertion_export_rows(); SQL injection policy updated with new audited sites and trusted identifier names.
Snapshots and docs for CLI changes
tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr, tests/unit/cli/__snapshots__/test_help_snapshots.ambr, tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr, tests/unit/cli/test_click_app.py, tests/unit/cli/test_diagnose_and_error_discipline.py, docs/test-quality-workflows.md
JSON status snapshot reflects incremented user-tier route counts and new list_assertion_claims route entry; all CLI help snapshots replace completions with continue and remove schema; docs add the help-ops-maintenance-assertion-export projection row.

Archive Query Response Shape Update

Layer / File(s) Summary
Query executor and web reader contract updates
tests/unit/cli/test_query_exec_laws.py, tests/unit/daemon/test_web_reader.py, tests/unit/daemon/test_daemon_cli.py, tests/unit/sources/test_live_batch_support.py
Multiple FakeArchiveStore.read_summary() implementations added; test assertions updated from flat session_id/source/block_id to nested items[*].session["id"]/items[*].match["message_id"] and item["id"] for pagination; web reader error substring gains /assertions/; USER_SCHEMA_VERSION constant replaces hard-coded literals.

Devtools Fixes and Test Infrastructure

Layer / File(s) Summary
Memory budget RSS fix and pytest verify improvements
devtools/query_memory_budget.py, devtools/verify.py
Post-loop peak_rss_kb = max(peak_rss_kb, peak_parent_rss_kb) added; _pytest_metadata_from_report prefers summary["total"]; _write_pytest_progress temp filename includes pid+monotonic-ns; _run report reading switches to _read_pytest_report.
xdist basetemp cleanup gating and test
tests/conftest.py, tests/unit/test_pytest_temp_policy.py
pytest_sessionfinish returns early when numprocesses is None/0/"0"; new test test_sessionfinish_leaves_xdist_basetemp_for_startup_sweep asserts basetemp is preserved when not in a parallel run.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • Sinity/polylogue#749: Directly modifies run_memory_budget peak RSS logic around peak_parent_rss_* and peak_rss_* — the same post-loop accounting this PR fixes.
  • Sinity/polylogue#1928: Implements soft-delete (status='deleted') semantics for assertion ledger entities, which this PR extends to feedback/correction archive persistence.
  • Sinity/polylogue#2074: Modifies devtools/verify.py live progress artifact writing and report handling — the same _write_pytest_progress and _run code paths changed in this PR.

Suggested labels

area:cli, area:storage, area:qa

🐇 A little rabbit dug through the archive with care,
Found old corrections tables — rewrote them to "assertions" there!
Now assertion-export hops out to the CLI,
Peak RSS is tallied after the loop goes by.
Soft deletes and nested fields — the burrow grows neat,
With JSONL and JSON for each row we greet! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding assertion export functionality for the user tier, which is the primary feature across multiple affected files.
Description check ✅ Passed The description comprehensively covers all required template sections: Summary (what changed and why), Problem (what the codebase needed), Solution (what was done with specific modules touched), Verification (exact commands and results), and Risks/Follow-ups (deferred work noted).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/assertion-user-export-1883

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 and usage tips.

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

ℹ️ 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
Sinity force-pushed the feature/feat/assertion-user-export-1883 branch from f6c6c91 to e10cf2f Compare June 18, 2026 10:45

@coderabbitai coderabbitai 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.

Actionable comments posted: 3

🤖 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 `@tests/unit/cli/test_archive_maintenance_cli.py`:
- Around line 51-55: The _seed_assertion_export_rows helper function is directly
creating and initializing the user.db database via sqlite3.connect and
initialize_archive_tier instead of using the proper test fixtures. Refactor this
function to accept workspace_env and SessionBuilder as parameters (or have the
calling tests use these fixtures) and use SessionBuilder to create the database
connection and perform initialization, replacing the direct sqlite3.connect call
and the explicit initialize_archive_tier invocation with the appropriate
SessionBuilder methods for proper test setup.

In `@tests/unit/storage/test_archive_tiers_assertions.py`:
- Around line 355-357: Refactor the test function
`test_list_assertions_for_export_covers_all_kinds_and_statuses` to use the
mandated fixture stack instead of directly initializing the database. Replace
the `tmp_path` parameter and `_connect` call with the `workspace_env` fixture
for isolated XDG paths and use `SessionBuilder` to set up the database
connection. If the test performs timestamp-sensitive operations, also add the
`frozen_clock` fixture as a parameter. Update the function signature and body to
accept these fixtures and use them for database initialization instead of the
current direct connection approach.

In `@tests/unit/storage/test_no_string_interpolated_sql.py`:
- Line 151: Remove the variable names `_assertion_columns`, `any_terms`, and
`session_clause` from the global `_TRUSTED_IDENTIFIER_NAMES` set since trusting
them globally bypasses safety checks for all future f-string SQL interpolations
without proper audit context. Instead, whitelist only the specific audited call
sites that legitimately use these variables by adding them to `_AUDITED_SITES`
with full context, ensuring each usage is explicitly reviewed and approved
rather than implicitly trusted by variable name.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 609c4fd6-6e4d-4971-a3a3-e137b0765b7a

📥 Commits

Reviewing files that changed from the base of the PR and between 72bbbcd and f6c6c91.

📒 Files selected for processing (21)
  • devtools/query_memory_budget.py
  • devtools/verify.py
  • docs/test-quality-workflows.md
  • polylogue/cli/commands/maintenance.py
  • polylogue/cli/commands/status.py
  • polylogue/storage/insights/feedback/__init__.py
  • polylogue/storage/sqlite/archive_tiers/user_write.py
  • tests/conftest.py
  • tests/unit/cli/__snapshots__/test_help_snapshots.ambr
  • tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr
  • tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr
  • tests/unit/cli/test_archive_maintenance_cli.py
  • tests/unit/cli/test_click_app.py
  • tests/unit/cli/test_diagnose_and_error_discipline.py
  • tests/unit/cli/test_query_exec_laws.py
  • tests/unit/daemon/test_daemon_cli.py
  • tests/unit/daemon/test_web_reader.py
  • tests/unit/sources/test_live_batch_support.py
  • tests/unit/storage/test_archive_tiers_assertions.py
  • tests/unit/storage/test_no_string_interpolated_sql.py
  • tests/unit/test_pytest_temp_policy.py

Comment on lines +51 to +55
def _seed_assertion_export_rows(archive_root: Path) -> None:
with sqlite3.connect(archive_root / "user.db") as conn:
conn.row_factory = sqlite3.Row
initialize_archive_tier(conn, ArchiveTier.USER)
upsert_assertion(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Replace direct SQLite seeding with the required test setup fixtures.

This helper bypasses the required test setup contract by creating and initializing user.db directly instead of using workspace_env and SessionBuilder.

As per coding guidelines, “For tests: use workspace_env fixture for isolated XDG paths, SessionBuilder for database setup, and frozen_clock fixture for timestamp-sensitive tests…”.

🤖 Prompt for 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.

In `@tests/unit/cli/test_archive_maintenance_cli.py` around lines 51 - 55, The
_seed_assertion_export_rows helper function is directly creating and
initializing the user.db database via sqlite3.connect and
initialize_archive_tier instead of using the proper test fixtures. Refactor this
function to accept workspace_env and SessionBuilder as parameters (or have the
calling tests use these fixtures) and use SessionBuilder to create the database
connection and perform initialization, replacing the direct sqlite3.connect call
and the explicit initialize_archive_tier invocation with the appropriate
SessionBuilder methods for proper test setup.

Source: Coding guidelines

Comment on lines +355 to +357
def test_list_assertions_for_export_covers_all_kinds_and_statuses(tmp_path: Path) -> None:
conn = _connect(tmp_path / "user.db")
try:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use the mandated test fixture stack for this new storage test.

This test initializes user.db via tmp_path/_connect rather than the required workspace_env + SessionBuilder setup contract for tests.

As per coding guidelines, “For tests: use workspace_env fixture for isolated XDG paths, SessionBuilder for database setup, and frozen_clock fixture for timestamp-sensitive tests…”.

🤖 Prompt for 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.

In `@tests/unit/storage/test_archive_tiers_assertions.py` around lines 355 - 357,
Refactor the test function
`test_list_assertions_for_export_covers_all_kinds_and_statuses` to use the
mandated fixture stack instead of directly initializing the database. Replace
the `tmp_path` parameter and `_connect` call with the `workspace_env` fixture
for isolated XDG paths and use `SessionBuilder` to set up the database
connection. If the test performs timestamp-sensitive operations, also add the
`frozen_clock` fixture as a parameter. Update the function signature and body to
accept these fixtures and use them for database initialization instead of the
current direct connection approach.

Source: Coding guidelines

# compile-time SELECT column-list constants (record projections)
"_session_record_select",
"_message_record_select",
"_assertion_columns",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Avoid globally trusting clause-bearing SQL fragments by variable name.

Adding any_terms and session_clause to the global trusted-name set lets any future f-string SQL interpolation with those names bypass this safety test without site-specific audit context. Keep these out of _TRUSTED_IDENTIFIER_NAMES and whitelist only audited call sites in _AUDITED_SITES.

Suggested tightening
-        "any_terms",
-        "session_clause",

Also applies to: 167-168

🤖 Prompt for 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.

In `@tests/unit/storage/test_no_string_interpolated_sql.py` at line 151, Remove
the variable names `_assertion_columns`, `any_terms`, and `session_clause` from
the global `_TRUSTED_IDENTIFIER_NAMES` set since trusting them globally bypasses
safety checks for all future f-string SQL interpolations without proper audit
context. Instead, whitelist only the specific audited call sites that
legitimately use these variables by adding them to `_AUDITED_SITES` with full
context, ensuring each usage is explicitly reviewed and approved rather than
implicitly trusted by variable name.

@Sinity
Sinity force-pushed the feature/feat/assertion-user-export-1883 branch from e10cf2f to ba36dec Compare June 18, 2026 10:48
@Sinity
Sinity force-pushed the feature/feat/assertion-user-export-1883 branch from ba36dec to dd48264 Compare June 18, 2026 10:52
@Sinity

Sinity commented Jun 18, 2026

Copy link
Copy Markdown
Owner Author

Review follow-up at dd48264:\n\n- Fixed Codex P2: async correction listing now preserves valid flat assertion values as payloads, with regression coverage in tests/unit/insights/test_feedback.py.\n- Tightened the SQL interpolation audit per CodeRabbit: removed broad trusted names and moved assertion/session query interpolation to line-specific _AUDITED_SITES entries with rationale.\n- I did not apply the SessionBuilder fixture suggestion literally for user-tier assertion tests: these tests exercise the split user.db assertion helpers directly, and SessionBuilder is session/archive fixture infrastructure rather than the owner of user_tier.assertions. The tests still use isolated tmp/workspace roots and direct user-tier initialization where that is the unit under test.\n\nVerification after the fixes:\n- devtools test tests/unit/storage/test_no_string_interpolated_sql.py tests/unit/insights/test_feedback.py -k 'no_unaudited_string_interpolated_sql or audited_sites_are_real_violations or FeedbackStorage' -> 8 passed.\n- devtools verify --quick -> exit_code 0.

@Sinity
Sinity merged commit 7135ed3 into master Jun 18, 2026
14 checks passed
@Sinity
Sinity deleted the feature/feat/assertion-user-export-1883 branch June 18, 2026 10:59
@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.

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