Skip to content

feat(annotations): add enforced typed annotation foundation (#2756) - #2756

Closed
Sinity wants to merge 5 commits into
masterfrom
feature/annotations/schema-registry-safe
Closed

Sinity wants to merge 5 commits into
masterfrom
feature/annotations/schema-registry-safe

Conversation

@Sinity

@Sinity Sinity commented Jul 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Add the typed-annotation foundation: closed schema declarations, an explicit
registry, a schema-enforced assertion writer, and type-correct predicates over
JSON annotation values. This is the conflict-free replacement for PR #2752;
both PRs remain unmerged while this draft is reviewed.

Ref polylogue-rxdo.7

Problem

External labels currently degrade into untyped JSON blobs. The archive cannot
prove that a label was written under the active schema definition, and query
predicates cannot reliably distinguish JSON strings, numbers, booleans, and
null. The prior branch also diverged from current master and accumulated
conflicts, so publishing a fresh branch avoids rewriting its public history.

Solution

  • Add closed AnnotationField and AnnotationSchema models plus an explicit
    AnnotationSchemaRegistry in polylogue/annotations/schema.py.
  • Validate all writes against the exact active registered schema, rejecting
    unknown, draft, deprecated, drifted, and non-finite values. Runtime
    declarations reject unknown closed-vocabulary values and non-finite bounds;
    arbitrarily large finite JSON integers do not pass through float coercion.
  • Route validated external-agent rows through the existing assertion write
    chokepoint, preserving candidate/non-injected safety semantics.
  • Add value.<path> equality and range predicates for assertion queries. SQL
    guards JSON type before comparison, so strings, numbers, booleans, null, and
    missing paths remain distinct; equality alternation preserves each scalar's
    identity and numeric ranges reject non-finite right-hand sides.
  • Add production-route write/query/judge coverage and regenerate the topology
    projection for the three new annotation modules.

Acceptance criteria

Satisfied in this foundation phase:

  • closed typed field declarations and finite numeric values/bounds
  • exact active registered-schema enforcement at the public writer
  • candidate/non-injected writes through the production assertion chokepoint
  • typed JSON scalar equality and numeric range predicates
  • real archive write/query/judge tests

Explicitly deferred:

  • polylogue-rxdo.7.1: durable annotation_schemas and
    annotation_batches, immutable fingerprints, a concrete
    delegation-discourse schema, and queryable batch provenance
  • polylogue-rxdo.7.2: bounded JSONL import, live target/evidence-span
    validation, CLI/MCP contracts, disagreement/adjudication roundtrips, and
    rendering
  • polylogue-kmts: structural-target joins without row multiplication

The parent bead remains open; neither child is optional for its full
acceptance criteria.

Verification

  • devtools test tests/unit/annotations/test_schema.py tests/unit/annotations/test_write.py tests/unit/cli/test_query_expression.py tests/unit/storage/test_archive_tiers_assertion_write_through.py
    -> 485 passed, 1 skipped in 279.26s at the foundation head
  • consolidated adversarial-regression selector over schema closure, finite
    values/bounds, scalar identity/alternation, and public-writer rejection
    -> 23 passed, 14707 deselected in 24.31s
  • devtools verify --quick at b8b2c823a
    -> all 15 steps exited 0 in 27.43s, including mypy, generated surfaces,
    topology, layering, schema roundtrip, and safety gates
  • pre-push devtools verify --quick at b8b2c823a
    -> all 15 steps exited 0 in 26.33s

GitHub-hosted jobs currently fail before startup because the repository account
is billing-locked; no job log or substantive CI failure was produced. The PR
remains draft pending coordination with the overlapping topology change.

Anti-vacuity: the focused tests exercise the real SQLite assertion writer,
typed SQL lowering, archive query readback, and candidate judgment. Removing
the active-registry check, finite guards, JSON-type equality guard, or
candidate chokepoint causes the corresponding production-route regression to
fail. The equality fixture places true beside numeric 1, and false beside
numeric 0, so SQLite coercion cannot pass unnoticed.

Adversarial review notes

The independent audit found four real gaps: boolean/number equality coercion,
missing runtime enforcement of closed declaration vocabularies, accepted
non-finite bounds/equality literals, and OverflowError on huge finite integer
validation. Commit b8b2c823a repairs all four and adds mutation-sensitive
regressions. No Beads item was closed; the parent and both residual phases stay
open.

Sinity and others added 4 commits July 12, 2026 11:14
…ates

Problem: polylogue-rxdo.7 asks for the missing external-agent-labeling
loop (export evidence -> label under a declared schema -> import as
candidates -> query back -> judge -> report). Storage was ~75% ready
(assertions table, upsert chokepoint, judge lifecycle all real) but two
foundations were missing: labels had no declared shape (queryable JSON
blobs, not analytical variables), and the DSL's `value` field on the
`assertion` unit was substring-only, unable to express `value.score>=4`.

What changed: this is the first coherent slice of the larger bead --
schema registry + typed value predicates, since the annotation_batches
provenance container and JSONL/CLI/MCP import surface build on this
foundation (per the bead's own scoping note).

- polylogue/annotations/schema.py: AnnotationField/AnnotationSchema
  declarations (typed value shape, target ObjectRefKind grain,
  evidence policy, abstention convention) plus a registry and
  validate_annotation_value/validate_annotation_row.
- polylogue/annotations/write.py: upsert_annotation_assertion(), the
  atomic single-row write a future batch importer would loop over --
  validates a label against a schema, then writes through the existing
  single assertion-write chokepoint (upsert_assertion), inheriting its
  37t.15 agent-authored candidate-coercion invariant for free. Uses a
  distinct id-derivation namespace from the existing freeform
  upsert_annotation() note helper so the two "annotation" concepts
  never collide on identity.
- polylogue/archive/query/expression.py: the `assertion` unit now
  accepts dynamic `value.<dotted.path>` fields with `=`/`>`/`>=`/`<`/
  `<=` operators (`value.score:>=4`, `value.status:approved`),
  lowered in polylogue/storage/sqlite/archive_tiers/archive.py via
  `json_extract(value_json, '$.path')` (bound parameter, CAST AS REAL
  for comparison operators). Other units continue to reject
  `value.*` as unknown fields.
- docs/plans/topology-target.yaml, docs/topology-status.md: topology
  projection regenerated for the new polylogue/annotations/ package
  (also picked up pre-existing stale LOC entries for a few unrelated
  files -- topology regen recomputes every file, not just this diff's).

Deferred (explicitly, tracked in the bead): the annotation_batches
provenance container, a JSONL/CLI/MCP import surface that loops over
upsert_annotation_assertion for many rows, a concrete registered
delegation-discourse schema (belongs to the consuming Fable campaign,
polylogue-212.9.1), and referential-integrity checking of target/
evidence refs against the live archive (this slice validates ref
*shape*, not that the ref resolves to a real row -- that needs the
batch importer's archive handle).

Verification:
- devtools test tests/unit/annotations/test_schema.py
  tests/unit/annotations/test_write.py
  tests/unit/cli/test_query_expression.py
  tests/unit/storage/test_archive_tiers_assertion_write_through.py
  -> 463 passed, 1 skipped (pre-existing skip, unrelated).
- devtools test tests/unit/storage/test_archive_tiers_assertions.py
  -> 25 passed, 1 failed; confirmed via git stash the failure
  (test_fresh_user_tier_has_no_legacy_overlay_tables, a stale
  `context_deliveries` table-set expectation) is pre-existing on
  master, unrelated to this diff.
- mypy --strict on every touched/new file -> no issues.
- ruff format --check / ruff check on every touched/new file -> clean.
- devtools render topology-projection && devtools render
  topology-status; devtools render all --check -> no drift.
- Manual roundtrip smoke test (schema-validated candidate write ->
  value.score/value.status DSL query -> judge accept -> active row
  visible via value.score:>=4 AND status:active) exercised end to end
  against a real sqlite archive before writing the pinned test.

Ref polylogue-rxdo.7

Co-Authored-By: Claude <[email protected]>
Problem: the annotation foundation allowed unregistered or drifted schema definitions to share one provenance identity, and typed value predicates could coerce strings and booleans into numeric matches or lose JSON scalar type during equality queries.\n\nWhat changed: require an exact active registry definition at the public annotation writer, reject non-finite analytical numbers, preserve quoted JSON scalar literals and alternations in the DSL, and guard range comparisons with SQLite JSON type checks. Production-route tests cover writer rejection, candidate writes, typed SQLite queries, and judgment promotion.\n\nRef polylogue-rxdo.7\n\nCo-Authored-By: Claude <[email protected]>
Problem: the latest Fable integration note defines a broader campaign slice than PR #2752 can honestly satisfy without a durable user-tier migration and new CLI/MCP surfaces.\n\nWhat changed: retain the parent acceptance criteria, correct the phase claim, and track durable schema/batch storage plus JSONL import and public surfaces as execution-grade child beads. The parent remains open until both children land.\n\nRef polylogue-rxdo.7\n\nCo-Authored-By: Claude <[email protected]>
Regenerate the topology projection after adding the typed annotation
foundation. This records the three new stable modules and refreshes
affected source line counts against current master.

Ref polylogue-rxdo.7

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

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 5ff529a1-df6b-4232-a7c9-85a44627075f

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/annotations/schema-registry-safe

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): add enforced typed annotation foundation feat(annotations): add enforced typed annotation foundation (#2756) Jul 12, 2026
Problem: typed annotation equality still allowed SQLite to conflate JSON booleans with numeric zero/one, while schema declarations accepted invalid closed-vocabulary values and non-finite bounds. Huge integers could also raise OverflowError during finite-number validation.

Guard equality by SQLite JSON type as well as extracted value, reject non-scalar and non-finite query literals, validate every closed declaration vocabulary at construction, and handle arbitrary-size finite integers without float coercion. Add production-route regressions for writer validation, boolean/number/null/missing alternation, and finite bounds.

Ref polylogue-rxdo.7

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 12, 2026
…2757)

## Summary

Add the typed-annotation foundation on current master: closed schema
declarations, an explicit registry, a schema-enforced assertion writer,
and
type-correct predicates over JSON annotation values. This fresh branch
replaces
unmerged PRs #2752 and #2756 without rewriting their published history
and is
based on master `7fd5b6bb9` after PR #2755.

Ref polylogue-rxdo.7

## Problem

External labels currently degrade into untyped JSON blobs. The archive
cannot
prove that a label was written under the active schema definition, and
query
predicates cannot reliably distinguish JSON strings, numbers, booleans,
and
null. The earlier branches predated merged topology changes; a fresh
branch is
required to preserve public history and regenerate derived surfaces
against
current master.

## Solution

- Add closed `AnnotationField` and `AnnotationSchema` models plus an
explicit
  `AnnotationSchemaRegistry` in `polylogue/annotations/schema.py`.
- Validate all writes against the exact active registered schema,
rejecting
  unknown, draft, deprecated, drifted, and non-finite values. Runtime
declarations reject unknown closed-vocabulary values and non-finite
bounds;
arbitrarily large finite JSON integers do not pass through float
coercion.
- Route validated external-agent rows through the existing assertion
write
  chokepoint, preserving candidate/non-injected safety semantics.
- Add `value.<path>` equality and range predicates for assertion
queries. SQL
guards JSON type before comparison, so strings, numbers, booleans, null,
and
missing paths remain distinct; equality alternation preserves each
scalar's
  identity and numeric ranges reject non-finite right-hand sides.
- Semantically carry forward the latest `polylogue-rxdo.7` record plus
open
  children `.7.1` and `.7.2`, preserving unrelated master Beads records.
- Regenerate topology projection/status against merged PR #2755 master.

## Acceptance criteria

Satisfied in this foundation phase:

- closed typed field declarations and finite numeric values/bounds
- exact active registered-schema enforcement at the public writer
- candidate/non-injected writes through the production assertion
chokepoint
- typed JSON scalar equality and numeric range predicates
- real archive write/query/judge tests

Explicitly deferred:

- `polylogue-rxdo.7.1`: durable `annotation_schemas` and
  `annotation_batches`, immutable fingerprints, a concrete
  delegation-discourse schema, and queryable batch provenance
- `polylogue-rxdo.7.2`: bounded JSONL import, live target/evidence-span
validation, CLI/MCP contracts, disagreement/adjudication roundtrips, and
  rendering
- `polylogue-kmts`: structural-target joins without row multiplication

The parent bead remains open; neither child is optional for its full
acceptance criteria. No prior PR or bead changes state through this PR
body.

## Verification

- consolidated fresh-master regression selector over schema closure,
finite
values/bounds, scalar identity/alternation, and public-writer rejection
  -> `23 passed, 14733 deselected in 25.18s`
- `devtools verify --quick` with the regenerated/merged working tree
-> all 15 steps exited 0 in 47.63s, including mypy, generated surfaces,
  topology, layering, schema roundtrip, and safety gates
- pre-push `devtools verify --quick` at `c7d1349c6`
  -> all 15 steps exited 0 in 23.53s
- `devtools render topology-projection && devtools render
topology-status`
  -> `917 rows`, `764 stable`, `6 TBD`
- `.agent/scripts/bd-graph-lint`
  -> `dup_labels=0`, `inversions=0`; two inherited missing-AC records
(`polylogue-2ilz`, `polylogue-nu2h`) are unchanged and outside this diff

GitHub-hosted jobs may still fail before startup while the repository
account
is billing-locked; that state produces no job logs or substantive CI
result.

Anti-vacuity: the focused tests exercise the real SQLite assertion
writer,
typed SQL lowering, archive query readback, and candidate judgment.
Removing
the active-registry check, finite guards, JSON-type equality guard, or
candidate chokepoint causes the corresponding production-route
regression to
fail. The equality fixture places `true` beside numeric `1`, and `false`
beside
numeric `0`, so SQLite coercion cannot pass unnoticed.

## Adversarial review notes

The independent audit of PR #2756 found four real gaps: boolean/number
equality
coercion, missing runtime enforcement of closed declaration
vocabularies,
accepted non-finite bounds/equality literals, and `OverflowError` on
huge finite
integer validation. Logical commit `ea1e75faf` carries the repair on
current
master with mutation-sensitive regressions. The replacement diff was
then
rechecked after merged PR #2755 and regenerated without carrying stale
topology
bytes.

---------

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

Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner Author

Superseded by merged PR #2757, rebuilt from post-#2755 master with the adversarial JSON scalar/finite-value fixes and regenerated topology.

@Sinity Sinity closed this Jul 12, 2026
@Sinity
Sinity deleted the feature/annotations/schema-registry-safe branch July 12, 2026 16:54
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