Skip to content

feat(annotations): persist durable labeling provenance (#2765) - #2765

Merged
Sinity merged 11 commits into
masterfrom
feature/feat/durable-annotation-provenance
Jul 12, 2026
Merged

Sinity merged 11 commits into
masterfrom
feature/feat/durable-annotation-provenance

Conversation

@Sinity

@Sinity Sinity commented Jul 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Persist versioned annotation schemas and independent annotation-batch provenance in the durable user tier. The change registers the concrete delegation.discourse@v1 schema, keeps complete repository reads, and exposes byte-bounded public batch-reference payloads.

Problem

The typed annotation foundation remained process-local: schema identity could drift across restarts, batches for the same target were not independently attributable, and public reference resolution could reflect arbitrarily large opaque values. Durable provenance also needed exact retry semantics without normalizing opaque ObjectRef identity.

Solution

  • Add the verified additive user.db v6 migration for annotation_schemas and annotation_batches, with canonical fresh-DDL parity and backup-manifest coverage.
  • Persist immutable schema declarations/fingerprints and reject incompatible id/version reuse, mutable aliases, NFC collisions, and invalid UTF-8 declarations.
  • Persist independent annotation-batch provenance, validation totals/failures, assertion refs, and batch-scoped insert-once assertions.
  • Preserve exact opaque ObjectRef bytes across hot/cold replay.
  • Resolve annotation-batch: refs through full durable reads while projecting bounded previews with exact counts, omitted-byte evidence, SHA-256 descriptors, and fixed-size invalid-Unicode fallbacks.
  • Regenerate topology/layering/documentation surfaces.

Built on the typed foundation from PR #2757. Ref polylogue-rxdo.7.1.

Acceptance criteria

  • Cold reopen resolves the same schema definition and fingerprint.
  • Incompatible schema id/version reuse fails closed.
  • delegation.discourse@v1 is registered.
  • Independent batches for the same schema/target remain distinguishable and queryable.
  • Durable v5→v6 migration requires verified backup evidence and matches fresh DDL.
  • Public batch-reference responses are byte bounded without truncating repository reads.

Deferred: JSONL/CLI/MCP batch import remains polylogue-rxdo.7.2; structural target joins remain polylogue-kmts.

Verification

  • devtools test ... — 155 focused durable/schema/ref/migration/public-route tests passed; run 20260712T152900Z-focused-test-3014481-3ad91648.
  • Final release-gap selection — 12 passed; run 20260712T160837Z-focused-test-3325379-546339d8.
  • Pre-push devtools verify --quick — 15/15 passed; run 20260712T161026Z-quick-3331317-d0b5478e.
  • devtools lab policy schema-versioning — 0 derived helpers, 0 invalid durable migrations.
  • .agent/scripts/bd-graph-lint — no cycles; only inherited missing-AC findings for polylogue-2ilz and polylogue-nu2h.
  • git diff --check — clean.

The default testmon selection expanded to 14,730 tests because surfaces/payloads.py is a dependency hub, so it was aborted rather than turned into a blanket suite run. devtools verify --all was not run.

Adversarial review

Five independent passes found and drove repairs for mutable schema aliases, NFC key collisions, hot/cold schema divergence, count-only response caps, unbounded missing refs, opaque-ref normalization, and invalid-Unicode escape paths. The fifth pass reported no other legitimate gaps after isolating its final lone-surrogate blocker; that blocker is fixed and regression-pinned.

Summary by CodeRabbit

  • New Features
    • Added durable, versioned annotation schema storage with canonical identity/fingerprints.
    • Added write-once annotation batch provenance storage with listing and filtering.
    • Annotation upserts can optionally link annotations to an immutable batch and validate drift.
    • Added annotation-batch reference resolution with bounded previews and truncation/caveat reporting.
    • Bundled the built-in “delegation discourse” annotation schema.
  • Documentation
    • Updated schema versioning, storage layout, and internal durability/topology docs for user annotation tiers (v6).
  • Bug Fixes
    • Fail-closed handling for malformed, oversized, and invalid-Unicode annotation-batch references.
  • Tests
    • Expanded durable storage and API contract coverage for schemas and batches.

Sinity and others added 9 commits July 12, 2026 17:07
Problem

Typed annotation schemas were process-local, and independent labeling runs
could overwrite the same assertion identity. A restart could not recover the
construct definition or trace a label to its batch-level actor, prompt,
source result, and validation accounting.

What changed

Advance user.db to schema version 6 through an additive verified-backup
migration. Persist canonical fingerprinted schema definitions, register the
concrete delegation-discourse schema, and store immutable annotation batch
provenance. Scope assertion identities to declared batch ObjectRefs and expose
focused ArchiveStore reads for schema and batch metadata.

Compatibility

Existing user.db v5 archives require the normal authenticated backup receipt
before migration. JSONL, CLI, and MCP import remain in polylogue-rxdo.7.2;
structural target joins remain in polylogue-kmts.

Verification

- devtools test focused annotation schema/write/storage and user migration
  routes: 80 collected, 78 passed before the shared SQL-comment fix; the two
  migration routes then passed, and the final durable route rerun passed 6/6
- devtools lab policy schema-versioning: schema evolution policy intact
- devtools verify --quick: all 15 steps passed
- git diff --check: clean

Ref polylogue-rxdo.7.1

Co-Authored-By: Claude <[email protected]>
Problem:
The durable annotation-schema batch introduced canonical identities, but
fresh import order, public ref resolution, Python-equal JSON values, and
post-judgment assertion retries still left coherence gaps. Nested mutable
provenance could also change the bytes written after construction.

What changed:
Make the storage import boundary lazy, resolve durable annotation-batch
refs through the archive facade, and compare schemas and batches by
canonical definitions. Capture batch provenance as an immutable snapshot,
reject NFC key collisions, validate persistence inputs, and preserve
insert-once assertion state across exact retries and operator judgment.
Strengthen durable migration, cold-reopen, corruption, and alias tests.

Verification:
- devtools test tests/unit/annotations/test_durable_storage.py
  tests/unit/storage/test_user_annotations_import.py (16 passed)
- devtools verify --quick (all 15 steps passed)
- devtools lab policy schema-versioning (policy intact)
- fresh adversarial closure review: NO LEGITIMATE GAPS

Ref polylogue-rxdo.7.1

Co-Authored-By: Claude <[email protected]>
Problem: annotation-batch ref resolution returned complete assertion and validation collections, arbitrary JSON documents, and duplicated every assertion in top-level object refs. Large durable batches therefore violated the bounded public-ref contract.

Project complete repository rows into capped public samples with exact totals and omissions. Represent arbitrary JSON as byte-bounded canonical prefixes with exact byte counts and SHA-256 identities, and surface explicit truncation caveats while preserving full repository reads.

Co-Authored-By: Claude <[email protected]>
Correct the merged foundation reference and persist the bounded public-ref
repair plus current-master verification receipts for polylogue-rxdo.7.1.

Co-Authored-By: Claude <[email protected]>
Normalize declaration strings before validation and snapshot caller-owned
field, enum, and target-kind sequences into immutable tuples. Hot registry
behavior now matches the canonical cold-reopen definition, while NFC
collisions and post-registration list mutation fail closed.

Co-Authored-By: Claude <[email protected]>
Represent public annotation provenance strings as fixed-budget previews with
exact UTF-8 totals and digests. Bound JSON previews, omit unsafe top-level
refs and actions when their authority is clipped, and report every count or
value truncation while preserving complete durable repository reads.

Co-Authored-By: Claude <[email protected]>
Problem:
Oversized missing or malformed annotation-batch refs could be echoed through unresolved responses. Canonical provenance also normalized opaque ObjectRef ids, and schema declarations deferred lone-surrogate failures until fingerprinting.

What changed:
Return a bounded digest descriptor for oversized batch-like misses, preserve exact ObjectRef UTF-8 identity through durable hot/cold replay, and reject invalid declaration Unicode at construction. Add production-route regressions for each boundary.

Verification:
devtools test <14 focused annotation/API cases>
devtools verify --quick (15/15 steps)

Co-Authored-By: Claude <[email protected]>
Problem:
Python public-ref inputs may contain lone surrogates even though UTF-8, JSON, and SQLite cannot represent them. The oversized-ref helper returned no descriptor for that case, allowing annotation-batch lookup to raise.

What changed:
Validate ref Unicode before parsing or opening the archive. Invalid inputs now return a fixed-size digest descriptor based on surrogatepass bytes, with exact code-point count and no raw input echo.

Verification:
devtools test <2 focused production resolver cases>
devtools verify --quick (15/15 steps)

Co-Authored-By: Claude <[email protected]>
Record the five-pass adversarial audit, the final bounded-ref repairs,
and the exact focused and quick verification receipts for rxdo.7.1.
Keep the deferred JSONL/MCP and structural-join scope explicit.

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

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

Next review available in: 55 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

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

How do review limits work?

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

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, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3c7d396e-9166-44c5-933a-c7ba410484ce

📥 Commits

Reviewing files that changed from the base of the PR and between 692d5a6 and 8c95276.

📒 Files selected for processing (4)
  • docs/internals.md
  • polylogue/storage/sqlite/archive_tiers/user.py
  • polylogue/storage/sqlite/migrations/user/006_annotation_schemas_batches.sql
  • tests/unit/storage/test_durable_migrations.py
📝 Walkthrough

Walkthrough

Changes

Annotation durability

Layer / File(s) Summary
Canonical annotation contracts
polylogue/annotations/*
Annotation schemas and batches enforce canonical validation, NFC normalization, fingerprints, immutable provenance, and batch-bound assertion writes.
User-tier persistence and migration
polylogue/storage/sqlite/archive_tiers/*, polylogue/storage/sqlite/migrations/user/*
User schema version 6 adds durable schema and batch tables, constraints, indexes, persistence helpers, and ArchiveStore APIs.
Bounded batch reference resolution
polylogue/api/archive.py, polylogue/surfaces/payloads.py
Annotation-batch references resolve from storage into bounded payloads with digest fallbacks and truncation caveats.
Durability and resolution validation
tests/unit/annotations/*, tests/unit/api/*, tests/unit/storage/*
Tests cover canonical identity, persistence, migrations, corruption handling, assertion replay, bounded payloads, and import behavior.
Durability metadata and documentation
CLAUDE.md, docs/*, .beads/issues.jsonl
Documentation, topology metadata, status reporting, durability descriptions, and the tracked issue are updated for annotation provenance storage.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant AnnotationWriter
  participant ArchiveStore
  participant UserAnnotations
  participant UserSQLite
  participant ArchiveFacade
  AnnotationWriter->>ArchiveStore: save_annotation_schema(schema)
  ArchiveStore->>UserAnnotations: persist_annotation_schema(schema)
  UserAnnotations->>UserSQLite: insert or verify canonical definition
  AnnotationWriter->>ArchiveStore: save_annotation_batch(batch)
  ArchiveStore->>UserAnnotations: persist_annotation_batch(batch)
  UserAnnotations->>UserSQLite: insert or verify canonical provenance
  ArchiveFacade->>ArchiveStore: get_annotation_batch(batch_id)
  ArchiveStore-->>ArchiveFacade: batch or missing result
  ArchiveFacade-->>AnnotationWriter: bounded annotation-batch payload
Loading

Possibly related issues

Suggested labels: area:schema

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 34.25% 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 is concise and accurately summarizes the main change: durable annotation provenance persistence.
Description check ✅ Passed The description covers Summary, Problem, Solution, and Verification well; it only omits explicit Changelog and Risks/Follow-ups sections.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/durable-annotation-provenance

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 Sinity changed the title feat(annotations): persist durable labeling provenance feat(annotations): persist durable labeling provenance (#2765) Jul 12, 2026
@Sinity
Sinity marked this pull request as ready for review July 12, 2026 16:12
@Sinity

Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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: 80b086a161

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

Comment thread polylogue/annotations/batch.py Resolved
Comment thread polylogue/annotations/write.py Resolved

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

🤖 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 `@docs/internals.md`:
- Around line 140-145: Update the User schema version 6 documentation to
identify the registered delegation schema as `delegation.discourse@v1`,
replacing the noncanonical `delegation-discourse v1` wording while preserving
the surrounding migration and table details.

In `@polylogue/storage/sqlite/migrations/user/006_annotation_schemas_batches.sql`:
- Around line 7-22: Update the definition_json CHECK constraint in
annotation_schemas to use IS instead of = for both json_extract comparisons
against schema_id and schema_version. Preserve the existing JSON validity and
object checks while ensuring missing or mismatched schema_id/version values fail
validation.
🪄 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: e7ff3423-c559-48a4-92ab-642a726416fa

📥 Commits

Reviewing files that changed from the base of the PR and between 9e1cc1e and 80b086a.

📒 Files selected for processing (27)
  • .beads/issues.jsonl
  • CLAUDE.md
  • docs/archive-backup.md
  • docs/internals.md
  • docs/plans/layering.yaml
  • docs/plans/topology-target.yaml
  • docs/schema.md
  • docs/topology-status.md
  • polylogue/annotations/__init__.py
  • polylogue/annotations/batch.py
  • polylogue/annotations/schema.py
  • polylogue/annotations/write.py
  • polylogue/api/archive.py
  • polylogue/cli/commands/status.py
  • polylogue/core/refs.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • polylogue/storage/sqlite/archive_tiers/user.py
  • polylogue/storage/sqlite/archive_tiers/user_annotations.py
  • polylogue/storage/sqlite/migrations/user/006_annotation_schemas_batches.sql
  • polylogue/surfaces/payloads.py
  • tests/unit/annotations/test_durable_storage.py
  • tests/unit/annotations/test_schema.py
  • tests/unit/api/test_facade_contracts.py
  • tests/unit/core/test_refs.py
  • tests/unit/storage/test_archive_tiers_assertions.py
  • tests/unit/storage/test_durable_migrations.py
  • tests/unit/storage/test_user_annotations_import.py

Comment thread docs/internals.md Resolved
Sinity added 2 commits July 12, 2026 19:14
Keep public annotation-batch references lossless when their object id ends with a colon, and retain the established mutable upsert behavior for assertions that are not batch-bound.\n\nAdd regression coverage for both contracts.\n\nCo-Authored-By: Claude <[email protected]>
Make the durable annotation schema CHECK reject missing JSON identity keys in both fresh DDL and the v6 migration, and document the canonical registered schema identifier.\n\nRegression coverage exercises migrated and fresh user tiers.\n\nCo-Authored-By: Claude <[email protected]>
@Sinity
Sinity merged commit 246c48d into master Jul 12, 2026
3 of 15 checks passed
@Sinity
Sinity deleted the feature/feat/durable-annotation-provenance branch July 12, 2026 17:20
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