Skip to content

test: restore suite collection + fix inherited stale-test failures - #1765

Merged
Sinity merged 4 commits into
masterfrom
feature/fix/inherited-test-failures
May 31, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/fix/inherited-test-failures

Conversation

@Sinity

@Sinity Sinity commented May 31, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fixes the inherited test failures that had accumulated on master, restores collection of the full unit suite, and surfaces two infrastructure findings: a 4-week CI gap and xdist flakiness that together explain why ~61 failures went unnoticed.

Problem

A full pytest tests/unit run on master reported 61 failures. Root-cause investigation found:

  1. The whole suite couldn't collect. tests/unit/cli/test_config_command.py ([bug] Secrets leak via polylogue config; secret/input write hardening #1748) imported tests.infra.app_env.make_app_env, but that helper module was never committed. pytest aborts on a collection error, so this one bad import masked the true suite state.
  2. test_iter_messages_keyset.py ([perf] Latent query-scaling hazards: O(M²) pagination, scan-on-completion, wasted sorts #1750) seeded messages via raw INSERT without content_hash, getting the schema '' default; the MessageRecord validator rejects empty content_hash on read-back (175 parametrized failures).
  3. Stale tests from real refactors that were never updated: schema bumped to 22, provider→source_name error wording, optional_datetime now UTC-aware (9735a6f), a new chunked-IN-clause SQL site needing an audit entry, CLI help/list output gaining new commands (commands, recent, --json, …).
  4. test_config_command.py voyage assertions drove the secret through the TOML [embedding] section, but the flat voyage_api_key secret is sourced from the VOYAGE_API_KEY env var (stripped by the autouse env-isolation fixture).

Why these accumulated — two infrastructure findings (need a follow-up)

  • CI has not run the test suite on master since 2026-05-02. ci.yml and nix.yml last ran on 9029a37a (2026-05-02); none of the ~20 commits merged since triggered them. Only Mutation Testing / Pages / Container / CodeQL run on recent commits. The unit-test gate has been effectively off for ~4 weeks — that is how 61 failures landed unnoticed. This is the highest-priority follow-up: fix the ci.yml/nix.yml trigger.
  • ~18 of the 61 are flaky under -n 16 xdist, not real. The entire tests/unit/mcp/test_tool_contracts.py cluster passes in isolation (60 passed) — they fail only under parallel workers (shared-state pollution). Brute-forcing the full suite with -n 16 manufactures failures; testmon / per-file runs are the right tool.

Solution

  • Restore tests/infra/app_env.py — an AppEnv with a StringIO-backed console (unblocks ~10k tests' collection).
  • test_iter_messages_keyset.py — fixtures set a non-empty content_hash (194 tests pass).
  • test_config_command.py — drive the voyage secret via VOYAGE_API_KEY; typed the dynamic console swap for mypy --strict.
  • Stale-test updates — schema 20→22; provider→source_name error match; optional_datetime UTC-aware; audit the chunked-IN-clause SQL site (trusted template + ?,? placeholders, values bound); regenerate the help/terminal snapshots for the new commands.
  • Regenerate drifted surfaces — AGENTS.md, docs/topology-status.md.

Verification

Targeted single-process runs (the brute-force full suite times out and flakes under xdist):

pytest tests/unit/storage/test_iter_messages_keyset.py   # 194 passed
pytest tests/unit/cli/test_config_command.py             # 8 passed
pytest <the 4 stale tests>                                # 4 passed
mypy --strict tests/infra/app_env.py tests/unit/cli/test_config_command.py  # clean
devtools verify --quick                                   # passes (push gate green)

Remaining (deferred — real deterministic failures, triaged)

A smaller set of confirmed-real failures remain (verified failing in isolation), needing per-case judgment — several are stale tests, a few may be real bugs and must not be masked:

  • test_resilience.py (4) — source_name == 'test' vs 'claude-code' (source/provider rename area)
  • test_acquisition_encoding.py (3) — BOM/zip handling
  • test_source_laws.py (2) — zip "File or stream is not seekable" (looks like a real bug)
  • test_fts_escape_in_insights.py (2), test_pipeline_probe.py (2), and assorted singles
  • test_repository_lifecycle_laws.py — a save-idempotency test-semantics question (double-seed then save_conversation correctly reports 0 changed)

These are intentionally NOT "fixed" by editing assertions, to avoid masking real regressions — they deserve review with fresh eyes.

Summary by CodeRabbit

  • New Features

    • Added --json CLI option as a shortcut for --format json with color and progress disabled.
    • Added new CLI commands: blackboard, commands, completions, config, context, context-pack, correlate, paths, raw, recent.
  • Documentation

    • Enhanced garbage collection documentation with detailed lifecycle explanations.
    • Updated CLI help output for improved display across different terminal widths.

Sinity added 4 commits May 31, 2026 03:47
…bugs

Three pre-existing failures unrelated to any feature work, surfaced once
the read-surface PR (#1763) ran the full suite:

- tests/infra/app_env.py was imported by test_config_command.py (#1748) but
  never committed, so pytest aborted collection of the WHOLE suite (one bad
  import). Restored the helper: an AppEnv with a StringIO-backed console.
- test_iter_messages_keyset.py (#1750) seeded messages via raw INSERT without
  content_hash, getting the schema '' default; the validating mapper rejects
  empty content_hash on read-back. Fixtures now set a non-empty hash (194 tests).
- test_config_command.py (#1748) asserted voyage_api_key redaction, but the flat
  voyage secret is sourced from the VOYAGE_API_KEY env var (stripped by the
  autouse env-isolation fixture), not the TOML [embedding] section. Drive the
  secret through its real source.
github-actions Bot pushed a commit that referenced this pull request May 31, 2026
@coderabbitai

coderabbitai Bot commented May 31, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR updates test infrastructure and validation assertions across the codebase: it introduces a make_app_env() factory for CLI test output capture, refreshes help snapshots to reflect new command options, adjusts test fixtures and storage/payload assertions to match schema updates, and documents the blob GC lease lifecycle in AGENTS.md.

Changes

Test Infrastructure and Validation Updates

Layer / File(s) Summary
CLI test output capture infrastructure
tests/infra/app_env.py
Introduces make_app_env() factory that constructs AppEnv with an in-memory rich Console configured for plain/no-ANSI output capture, enabling tests to assert on rendered help text and secret-redaction behavior via env.ui.console.file.getvalue().
Config command test fixture and output capture setup
tests/unit/cli/test_config_command.py
Modifies config_with_secrets fixture to set VOYAGE_API_KEY in environment and updates _run helper to extract console output via StringIO/Console casting, enabling redaction assertions on empty-string API key values rendered as <unset>.
CLI help output snapshots reflecting new --json option and commands
tests/unit/cli/__snapshots__/test_help_snapshots.ambr, tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr
Updates snapshots across standard/narrow/wide terminal widths to include --json shortcut option description and new command entries (blackboard, commands, completions, config, context, context-pack, correlate, paths, raw, recent) in the expected positions.
Storage schema and message seeding test updates
tests/unit/storage/test_dead_schema_sweep.py, tests/unit/storage/test_iter_messages_keyset.py, tests/unit/storage/test_no_string_interpolated_sql.py
Pins SCHEMA_VERSION == 22, adds content_hash column to message seeding INSERT statements in keyset pagination tests, and documents trusted SQL interpolation site for IN-clause parameter binding in audit whitelist.
Payload validation and parameter name test updates
tests/unit/lib/test_payload_coercion.py, tests/unit/pipeline/test_pipeline_ids.py
Imports UTC and constructs UTC-aware datetime test inputs for payload validation, updates conversation_id validation error assertion to reference renamed source_name parameter.
GC lease documentation and generated topology status
AGENTS.md, docs/topology-status.md
Expands GC concurrency model docs with detailed blob lease try/finally wrapping, daemon orphaned-lease sweep, and gc_generations defense-in-depth age-gating logic; updates placement-domain file count snapshot.

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly Related PRs

  • Sinity/polylogue#1015: Introduces the blob-lease plus snapshot reference check GC design that AGENTS.md now elaborates with lease lifecycle and orphaned-sweep details.
  • Sinity/polylogue#1754: Implements the blob-lease try/finally, orphaned-lease sweep, and gc_generations age-gating logic (max(MIN_AGE_S, now - prev_generation.completed_at)) that this PR documents.
  • Sinity/polylogue#402: Refreshes CLI help baseline fixtures and command output; this PR updates the same help snapshots for alignment with new --json option and command list.

Suggested Labels

area:storage, area:cli, area:qa

Poem

🐰 A PR hops in with tests so neat,
CLI snapshots keep their beat,
Leases documented, schemas refined,
Infrastructure aligned—what a find!
Help output refreshed, fixtures set tight,
All tests coordinated just right. ✨

🚥 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 'test: restore suite collection + fix inherited stale-test failures' directly and clearly summarizes the main change — restoring test suite collection and fixing accumulated test failures.
Description check ✅ Passed The description follows the template structure with all required sections: Summary, Problem, Solution, and Verification are comprehensive and well-documented. Changelog is appropriately skipped as this is a test-only PR. Risks and Follow-ups section is included with findings about CI gaps and xdist flakiness.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/inherited-test-failures

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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/unit/cli/__snapshots__/test_help_snapshots.ambr (1)

155-183: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix empty --help short descriptions for blackboard, commands, and recent (and facets)

polylogue/cli/click_command_registration.py registers root commands via _L(...) with short_help=_SHORT_HELP.get(name); keys for blackboard, commands, and facets are missing from _SHORT_HELP, so Click renders blank short-help even though the command functions have docstrings.
polylogue/cli/click_app.py registers query verbs via _LazyCommand(..., short_help=_QUERY_VERB_HELP.get(_verb)); _QUERY_VERB_HELP has no "recent", so recent also renders blank.

🤖 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/__snapshots__/test_help_snapshots.ambr` around lines 155 -
183, The root cause is missing short-help entries for several commands: add
entries for "blackboard", "commands", and "facets" to the _SHORT_HELP mapping
used by _L(...) in polylogue/cli/click_command_registration.py, and add "recent"
to the _QUERY_VERB_HELP mapping used by _LazyCommand in
polylogue/cli/click_app.py; each new key should provide a concise short_help
string (or derive one from the command function's docstring) so Click displays
non-empty short descriptions for those commands.
🤖 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.

Outside diff comments:
In `@tests/unit/cli/__snapshots__/test_help_snapshots.ambr`:
- Around line 155-183: The root cause is missing short-help entries for several
commands: add entries for "blackboard", "commands", and "facets" to the
_SHORT_HELP mapping used by _L(...) in
polylogue/cli/click_command_registration.py, and add "recent" to the
_QUERY_VERB_HELP mapping used by _LazyCommand in polylogue/cli/click_app.py;
each new key should provide a concise short_help string (or derive one from the
command function's docstring) so Click displays non-empty short descriptions for
those commands.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: da1f1287-bd73-466f-a78a-ec88d7b23f15

📥 Commits

Reviewing files that changed from the base of the PR and between 9f037ae and e854cc5.

📒 Files selected for processing (11)
  • AGENTS.md
  • docs/topology-status.md
  • tests/infra/app_env.py
  • tests/unit/cli/__snapshots__/test_help_snapshots.ambr
  • tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr
  • tests/unit/cli/test_config_command.py
  • tests/unit/lib/test_payload_coercion.py
  • tests/unit/pipeline/test_pipeline_ids.py
  • tests/unit/storage/test_dead_schema_sweep.py
  • tests/unit/storage/test_iter_messages_keyset.py
  • tests/unit/storage/test_no_string_interpolated_sql.py

@Sinity
Sinity merged commit b605465 into master May 31, 2026
5 checks passed
@Sinity
Sinity deleted the feature/fix/inherited-test-failures branch May 31, 2026 09:07
Sinity added a commit that referenced this pull request May 31, 2026
…ns (#1767)

## Summary

Continues clearing the inherited test failures (after #1765). Fixes one
real search bug, one real #1737 docs-cleanup gap, and three stale
surface pins.

## Problem & Solution

Failures that accumulated while CI was off (#1766):

1. **`escape_fts5_query` bug** (`fts_escape_in_insights`): bare-asterisk
queries like `* * *` passed through unquoted and SQLite rejected them
(`unknown special query: *`). The prefix logic treated any
`*`-at-word-boundary as valid `word*` syntax. Now only word-suffixed `*`
is preserved; bare asterisks are quoted (safe literal). Updated the
`test*` security case to the preserved-prefix form (still
MATCH-compiles).
2. **Dangling verification docs** (`render_docs_surface`): #1737 deleted
`docs/verification-catalog.md` and `docs/verification-lab.md` but left
their entries in `devtools/docs_surface.py`; the renderer skipped the
missing files so the README dropped them and the pin failed. Removed the
dead entries + test assertion; regenerated the docs README.
3. **Stale surface pins**: `perf_rescue_1314` (v22 moved per-role counts
to `conversation_stats`, eliminating the messages scan — dropped the
stale assertion); `click_app` (registered 6 new commands);
`message_render_envelope` (added `paste_boundary_state`, #1655).

## Verification

```
pytest tests/unit/storage/test_fts_escape_in_insights.py tests/unit/storage/test_query_security.py  # 46 passed
pytest <perf_rescue, click_app, envelope, render_docs_surface>  # all pass
devtools verify --quick  # push gate green
```

## Remaining (tracked for follow-up)

Still-open inherited failures, triaged in #1765's body — needing
per-case judgment: the `ASSURANCE_REGISTRY` real gap (6 new commands
need output contracts), `exercise_catalog`/`config source_roots`
(ambiguous), and the slower real candidates `test_source_laws` (zip "not
seekable" — likely a real regression), `test_resilience` (source_name),
`test_acquisition_encoding` (BOM).
Sinity added a commit that referenced this pull request May 31, 2026
## Problem

Every JSON conversation export packaged inside a `.zip` (ChatGPT/Claude
web exports) silently failed to ingest with `File or stream is not
seekable` and was skipped.

`process_zip` opens each entry via `zipfile.ZipExtFile` (non-seekable).
For individual-JSON entries the path is `emit → _emit_individual →
_iter_json_stream → iter_json_stream_with`, which rewinds with
`handle.seek(0)` between its ijson multi-strategy attempts. A zip entry
can't seek, so the parse raised and the file was dropped at the
acquisition boundary. (`_emit_grouped` already materialized to
`BytesIO`; the individual path did not.)

This is a real ingestion regression for zipped exports — surfaced once
the suite could collect again (#1765) and confirmed by tracing the
swallowed exception at `source_parsing.py:163`.

## Solution

In `iter_json_stream_with`, before the seeking strategies, materialize a
non-seekable handle into a `BytesIO` once (the function inherently
requires seeking; bounded zip entries are safe to read fully). Added the
missing `import io`.

## Verification

```
pytest tests/unit/sources/test_source_laws.py tests/unit/sources/test_acquisition_encoding.py  # 123 passed (was 5 failing)
```
Fixes the zip round-trip, raw-capture, multi-conversation-zip,
BOM-in-zip, and partial-corruption cases.
Sinity added a commit that referenced this pull request May 31, 2026
## Summary

Three more inherited-failure fixes (continuing #1765/#1767/#1768).

## Changes

- **`blackboard list --limit`**: used `-n`, violating the repo-wide
`-l/--limit` convention enforced by `test_flag_aliases_consistent`.
Aligned to `-l` (small CLI fix).
- **`exercise_catalog`**: dropped the `insights analytics` nested path
from the pin — that command path no longer exists.
- **`config source_roots`**: the TOML serializer now renders arrays
multi-line (`roots = [\n "/a",\n "/b",\n]`); the test pinned the old
single-line spelling. Assert the array shape + members robustly.
(Confirmed the cli-override is correctly applied — it was purely a
formatting-style drift.)

## Verification

```
pytest <theme_aliases, exercise_catalog, config source_roots, help/terminal snapshots>  # all pass
```

## Deferred (intentionally not touched)

The remaining inherited failures cluster on the **in-flux
`provider`/`source_name` vocabulary** (#1743 is actively redesigning
this) and a product decision — editing them blind risks encoding the
wrong interpretation:
- `resilience` (4), `ingestion_chaos`, `parsing_service`,
`pipeline_probe` (2), `parsers_local_agent` — all turn on parsed
`source_name` being the source-config name (`'test'`) vs the detected
origin (`'claude-code'`/`'codex'`). Likely a real regression in the
origin-vs-source conflation, but it belongs to the #1743 redesign or an
explicit operator call.
- `ASSURANCE_REGISTRY` — the 6 new commands need declared output
contracts (#1272), a per-command product decision.
Sinity added a commit that referenced this pull request Jun 5, 2026
…1766)

## Summary

Restores the `push` / `pull_request` CI triggers that were
**accidentally removed** by #718, re-enabling automatic test/lint/nix
gating on `master` and PRs.

## Problem

#718 (`refactor(cli): remove foreground resource policy`) — a PR whose
scope was entirely CLI resource policy, with **no mention of CI** —
silently reverted the trigger blocks on four workflows, leaving each
with only `workflow_dispatch:` (manual-only):

| Workflow | Before #718 | After #718 |
|----------|-------------|------------|
| `ci.yml` (lint + test ×3 Python) | push + pull_request | **dispatch
only** |
| `nix.yml` (nix build + flake check) | push + pull_request | **dispatch
only** |
| `actionlint.yml` | pull_request | **dispatch only** |
| `dep-audit.yml` | push + pull_request + weekly schedule | **dispatch
only** |

Consequence: the CI test gate has not run automatically since
**2026-05-02** (the last `ci.yml`/`nix.yml` runs are on `9029a37a`).
Across the ~20 commits merged since, **~61 unit-test failures
accumulated undetected** — see #1765. This is the root cause of the test
debt.

(`pr-policy.yml` and `proof-comment.yml` were also gutted by #718, but
those stay deleted — that was the intentional ceremonial-verification
cleanup in #1737, not collateral. `codeql.yml` retains a working trigger
and is unaffected.)

## Solution

Restore the exact pre-#718 `on:` blocks (verified against `git show
8b2b0fa~1:.github/workflows/<f>.yml`):
- `ci.yml` / `nix.yml`: `push: [master]` + `pull_request: [master]`
(opened/reopened/synchronize/ready_for_review)
- `actionlint.yml`: `pull_request: [master]` (paths:
`.github/workflows/**`, `.github/actions/**`)
- `dep-audit.yml`: push/pull_request (paths: `pyproject.toml`,
`uv.lock`, the workflow) + weekly `cron: 0 6 * * 1`

## Verification

```
python3 -c "import yaml; ..."  # all four on: blocks parse with push/pull_request restored
```

## ⚠️ Expected: re-enabling CI surfaces the pre-existing failures

Once merged, `ci.yml` will run on `master` and PRs and will be **red**
until the inherited test failures are cleared. That is the intended
signal, not a regression introduced here. The known failures are partly
fixed in **#1765** (collection error, keyset, config, stale tests) and
partly still open (a handful of real-bug candidates triaged in #1765's
body). Recommended order: merge #1765, work the remaining real failures,
then this fix's CI will go green. Merging this first is also fine — it
just makes the existing red state visible.


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

## Summary by CodeRabbit

* **Chores**
* Enhanced workflow triggers to automatically run validation checks on
pull requests and commits targeting the master branch, improving
consistency of continuous integration checks.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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