Skip to content

test(storage): pin blob-store + schema-policy invariants (#1185) - #1189

Merged
Sinity merged 1 commit into
masterfrom
feature/test/storage-invariants-1185
May 17, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/test/storage-invariants-1185

Conversation

@Sinity

@Sinity Sinity commented May 17, 2026

Copy link
Copy Markdown
Owner

Summary

Add two contract suites that pin the documented invariants of the blob store and the schema-version policy from docs/internals.md, distinct from the happy-path CRUD coverage in test_blob_store.py / test_blob_gc.py / test_schema_upgrades.py.

Problem

#997's closeout flagged the blob store and the schema-migration policy among uncovered domains. Existing storage tests cover specific behaviors (write paths, individual upgrade plans, GC regression bugs) but do not pin the documented invariants themselves. A refactor or accidental drift could change the contract without any test failing.

Solution

Two new test files, each docstring-citing the docs/internals.md section it pins:

tests/unit/storage/test_blob_store_contracts.py (16 tests, including a 6-variant parametrize) pins § "Blob Store Model" and § "GC concurrency model — leases plus snapshot reference check":

  • Content-addressing determinism across write_from_bytes / write_from_fileobj / write_from_path and across empty / single-byte / ASCII / multibyte UTF-8 / binary / multi-MiB chunked payloads.
  • Prefix-shard layout: {root}/{hash[:2]}/{hash[2:]}, with the full 256-shard hex namespace permitted and non-shard noise (wrong-length dirs, scratch dirs) ignored by iter_all.
  • Write-once semantics: re-write of the same hash is a no-op (same inode, same mtime), corruption is not silently overwritten by a re-write, and the trust boundary is the hash not the bytes.
  • Dedup convergence across all three write methods.
  • Orphan detection scoping (only unreferenced blobs surface).
  • GC concurrency: DB-reference and lease predicates are independent invariants, leases acquired via acquire_blob_leases are visible to fresh reader connections immediately (the immediate-commit contract the docs make explicit), generation rows are recorded on each GC cycle that has candidates, and a leased in-flight blob survives GC even when the snapshot reference check says "orphan".
  • link_group_key isolation on artifact_observations — the docs' "blob_links" vocabulary describes this same grouping table; group-A queries must not surface group-B rows, and null-group rows are not surfaced by either.

tests/unit/storage/test_schema_policy_contracts.py (9 tests) pins § "Schema Versioning Model" and the canonical FTS trigger set from § "Daemon Convergence Evidence":

  • Fresh init bootstraps to SCHEMA_VERSION exactly.
  • Matching version opens cleanly (idempotent re-open).
  • SCHEMA_VERSION + 1 (future) is rejected on the sync path.
  • An unknown older version (planted v1) is rejected — pins "rejected rather than partially patched with additive DDL".
  • The async bootstrap path enforces the same policy (async is the primary runtime; a sync-only check would be a hole).
  • The read-only open path (assert_readable_archive_layout) also rejects.
  • decide_schema_bootstrap returns version_mismatch action for unknown versions — pins the policy decision, not just the side effect.
  • The diagnostic distinguishes newer-than-runtime from older-than-runtime so operators know whether to upgrade the runtime or run an in-place script.
  • Fresh init produces the canonical six FTS triggers (messages_fts_a{i,d,u}, action_events_fts_a{i,d,u}). A missing trigger is documented as an FTS index drift risk.

Each test's docstring cites the specific docs/internals.md section it pins so future doc/code drift is attributable.

Verification

nix develop -c pytest tests/unit/storage/test_blob_store_contracts.py tests/unit/storage/test_schema_policy_contracts.py
# 28 passed in 11.71s

nix develop -c devtools verify --quick
# exit_code: 0 (total_duration_s: 21.67)

Closes #1185

Add two contract suites pinning the documented invariants from
docs/internals.md:

- tests/unit/storage/test_blob_store_contracts.py covers content-
  addressing determinism (across all write methods + chunk
  boundaries), prefix-shard layout (first hex byte = shard), the
  iter_all walk's discipline against non-shard noise, write-once
  semantics, dedup convergence, orphan-detection scoping, and the
  GC concurrency model (DB-reference and lease predicates as
  independent invariants, immediate-commit lease visibility,
  generation tracking, link_group isolation in artifact_observations).

- tests/unit/storage/test_schema_policy_contracts.py covers the
  fresh-first policy: SCHEMA_VERSION authority, fresh-init produces
  the current version, matching version opens cleanly, future
  versions are rejected, unknown older versions are rejected on
  both sync and async paths, the read-only open path also rejects,
  the bootstrap decision is explicitly version_mismatch, the
  diagnostic message distinguishes newer from older, and fresh
  init creates the canonical 6-trigger FTS set
  (messages_fts_a{i,d,u}, action_events_fts_a{i,d,u}).

Each test cites the docs/internals.md section it pins in its
docstring so future doc/code drift is attributable.

Closes #1185
@coderabbitai

coderabbitai Bot commented May 17, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 4 minutes and 26 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 680fc2f2-41bb-4b92-bfa2-6920de94c085

📥 Commits

Reviewing files that changed from the base of the PR and between d42c6be and 0e4ab52.

📒 Files selected for processing (2)
  • tests/unit/storage/test_blob_store_contracts.py
  • tests/unit/storage/test_schema_policy_contracts.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/test/storage-invariants-1185

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.

@Sinity
Sinity merged commit 5254179 into master May 17, 2026
4 checks passed
@Sinity
Sinity deleted the feature/test/storage-invariants-1185 branch May 17, 2026 17:15

@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: 0e4ab52d8c

ℹ️ 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 added a commit that referenced this pull request May 18, 2026
…1190) (#1318)

## Summary

`run_blob_gc` now unlinks the correct sharded blob path
(`{root}/{prefix}/{remainder}`), increments `deleted` only when an
`unlink` actually removed a file, persists per-pass structured evidence
into a new `gc_generations.evidence` column, supports `dry_run=True`,
and exposes the evidence through a `polylogue maintenance gc-history`
operator surface.

## Problem

The previous implementation called
`(blob_path / blob_hash).unlink(missing_ok=True)` — i.e. it targeted
`{blob_dir}/{full_hash}`. Blobs live at the sharded path
`{blob_dir}/{prefix}/{remainder}` (see `BlobStore.blob_path`), so the
flat path never exists for a real blob. `missing_ok=True` silently
swallowed the `ENOENT` and the `deleted` counter bumped anyway, so:

- GC reports lied about reclamation.
- Orphan blobs were never actually removed.
- There was no audit trail beyond a row-count of completed generations.

This was observed during PR #1189 implementation and tracked in #1190.

## Solution

`polylogue/storage/blob_gc.py`:

- Added `_sharded_blob_path(blob_root, blob_hash)` mirroring
  `BlobStore.blob_path` and use it as the unlink target.
- Switched from `unlink(missing_ok=True)` to explicit
  `unlink()` with `FileNotFoundError` handling: missing files now
  bump `skipped_missing` instead of `deleted`.
- Split `PermissionError`/`OSError` failures into a separate
  `skipped_unlink_error` counter; the `deleted` counter only bumps on
  a successful `unlink()` call.
- Added a `GCRunEvidence` dataclass capturing inspected, deleted,
  per-reason skip counts (`skipped_referenced`, `skipped_leased`,
  `skipped_missing`, `skipped_unlink_error`), `dry_run`, `max_batch`,
  `previous_generation`, and the list of `deleted_hashes`. Serialised
  as sorted JSON.
- Added `dry_run: bool = False` kwarg: counts would-be deletions on
  disk-present candidates, touches no file, and does NOT write a
  `gc_generations` row (no generation slot consumed by previews).
- Added `read_gc_history(db_path, limit)` returning parsed history
  rows newest-first; pre-#1190 rows surface with `evidence=None` so
  they remain visible to operators.

`polylogue/storage/sqlite/schema_ddl_archive.py` /
`polylogue/storage/sqlite/schema_ddl.py`:

- Added `evidence TEXT` column to `gc_generations`.
- Bumped `SCHEMA_VERSION` 1 → 2. Per the no-migration-chain policy
  this is a deletes-then-defines edit: a mismatched DB triggers
  re-ingest (`polylogue reset --database && polylogued run`), no
  upgrade helper is added. The added column is nullable so existing
  in-place generations slot in cleanly under the new schema.

`polylogue/cli/commands/maintenance.py`:

- Added `polylogue maintenance gc-history` subcommand with `--limit`
  and `--output-format {plain,json}`. Reads `gc_generations.evidence`
  via `read_gc_history`; plain output shows generation, completion
  time, and the per-reason skip tallies.

Tests:

- `tests/unit/storage/test_blob_gc.py`:
  - `test_run_blob_gc_unlinks_sharded_path_and_increments_counter`
    plants an orphan via `BlobStore.write_from_bytes` (sharded path),
    backdates its mtime past `MIN_AGE_S`, runs GC, asserts the
    sharded file is gone AND counter == 1.
  - `test_run_blob_gc_does_not_increment_when_file_already_missing`
    patches `_candidate_blobs` to report a hash whose file was
    already removed; counter stays 0 and evidence records
    `skipped_missing >= 1`.
  - `test_run_blob_gc_dry_run_does_not_delete_or_record_generation`
    asserts dry-run preserves disk and consumes no generation slot.
  - `test_run_blob_gc_records_structured_evidence` validates the
    JSON shape, the deleted-hash list, and `skipped_referenced`
    accounting.
  - `test_read_gc_history_returns_recent_passes_newest_first` runs
    three GC passes and asserts newest-first ordering.
- `tests/unit/storage/test_blob_gc_concurrency.py`,
  `tests/unit/storage/test_blob_store_contracts.py`: schema fixtures
  updated to include the new `evidence` column; the threaded
  acquire/commit/GC test gained a pre-thread sentinel lease — the
  prior code's no-op unlink masked a real startup race between
  thread spawn and the writer's first `acquire_blob_leases` call.

Alternatives rejected:

- Keeping `missing_ok=True` and post-hoc checking `target.exists()`
  before/after would still race with concurrent reclaimers. Using
  the `unlink()` return-status idiom (FileNotFoundError ⇒ no-op) is
  atomic and matches POSIX semantics directly.
- Storing evidence in a sibling table was discarded as additional
  schema surface for no benefit; the evidence row is 1:1 with the
  generation and the JSON shape evolves more cheaply than columns.

## Verification

```
devtools verify --quick          # exit_code: 0
pytest tests/unit/storage/test_blob_gc.py \
       tests/unit/storage/test_blob_gc_concurrency.py \
       tests/unit/storage/test_blob_store_contracts.py
# 46 passed in 8.61s
```

Pre-existing CLI status test failures (`test_status_first_run_hint*`,
`test_status_subprocess_no_archive`) reproduce on master without these
changes — they read the host operator's 48.9 GB live archive instead
of an isolated tmp workspace, unrelated to GC.

Closes #1190
@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.

  • 79.F115 / P2: fixed-already at the checked revision: tests/unit/storage/test_schema_policy_contracts.py:343 now requires the exact older-version guidance to reset the derived index and rebuild it from source. Reusing newer-version guidance no longer passes merely because the embedded version numbers differ.

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.

test(storage): blob-store and schema-migration contract suites

1 participant