Skip to content

feat(storage): persist query provenance substrate - #2813

Merged
Sinity merged 2 commits into
masterfrom
feature/fanout/rxdo-substrate
Jul 13, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/fanout/rxdo-substrate

Conversation

@Sinity

@Sinity Sinity commented Jul 13, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds the first durable and operational query-provenance substrate: canonical
query identities, user-tier query/result manifests, and bounded ops-tier
query-run telemetry.

Problem

Queries were transient executions. They had no immutable public identity,
promoted result-manifest, or durable assertion target; existing saved-query
assertions remained tied to mutable saved-view ids.

Solution

  • core/query_identity.py specifies query:<hash>, query-run:qr_<id>, and
    result-set:<id> plus canonical planned-AST hashing.
  • User schema v7 adds immutable queries, mutable names, promoted result
    manifests/members, and planner edges. The verified migration repoints
    saved-query assertions in the same transaction.
  • Ops bootstrap DDL adds query_runs with only bounded result metadata; it
    never stores full membership.
  • SearchEnvelope exposes additive provenance fields and generated OpenAPI/CLI
    schemas are refreshed.

Verification

  • TMPDIR=/realm/tmp/polylogue-rxdo-substrate devtools test tests/unit/core/test_query_identity.py — 8 passed.
  • TMPDIR=/realm/tmp/polylogue-rxdo-substrate devtools test tests/unit/storage/test_query_objects.py tests/unit/storage/test_query_runs.py — 4 passed.
  • TMPDIR=/realm/tmp/polylogue-rxdo-substrate devtools test tests/unit/storage/test_durable_migrations.py — 33 passed; enters the verified-backup migration path and confirms saved-query assertions survive/repoint.
  • devtools lab policy schema-versioning — Schema evolution policy intact.
  • devtools verify --quick — passed before push and in the pre-push hook.

Acceptance matrix

Bead Criterion Status
polylogue-rxdo.2 Reordered AND operands hash identically Satisfied
polylogue-rxdo.2 Macro-repoint stability Deferred: parser-owned macro expansion must call the published canonical-plan boundary; no macro parser changes in this lane
polylogue-rxdo.2 Existing assertions survive migration Satisfied
polylogue-rxdo.2 Grain participates in promoted result-set identity Satisfied through grain-bearing manifest plus member uniqueness
polylogue-rxdo.3 Envelope fields are additive/generated Satisfied
polylogue-rxdo.3 Every committed query execution records and returns refs Remaining scope: execution-chokepoint queue/hook and CLI/MCP parity wiring
polylogue-rxdo.3 Previews create no rows Remaining scope: execution hook owns preview suppression
polylogue-rxdo.3 Promoted run survives ops reset Durable manifest schema is present; promotion command remains scope for the execution/lifecycle layer

Ref polylogue-rxdo.2
Ref polylogue-rxdo.3

Adversarial review notes

Iteration 1 found real implementation gaps: the execution recorder has no
production callers, envelopes are not populated, and @last/expiry, planner
integration, saved-name migration, virtual routine manifests, and the required
cross-surface/backpressure tests remain to be implemented. These are recorded
as remaining acceptance-matrix scope; this PR does not claim the two beads are
complete.

Summary by CodeRabbit

  • New Features

    • Added canonical identities for queries, query runs, and result sets.
    • Search responses now include optional query references, result fingerprints, and result exactness metadata.
    • Added durable storage for query definitions, names, result sets, and query relationships.
    • Added operational query-run recording with bounded sample metadata.
  • Documentation

    • Added Query Identity reference documentation.
    • Documented schema version 7 and updated API/schema references.
  • Tests

    • Added coverage for identity hashing, migrations, query storage, and query-run metadata.

@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: ed4672ef-7b9b-4174-9b20-66049b4b3ed2

📥 Commits

Reviewing files that changed from the base of the PR and between 69d73a5 and 17a7b1a.

📒 Files selected for processing (21)
  • devtools/docs_surface.py
  • docs/README.md
  • docs/internals.md
  • docs/openapi/search.yaml
  • docs/plans/layering.yaml
  • docs/plans/topology-target.yaml
  • docs/query-identity.md
  • docs/schemas/cli-output/search-envelope.schema.json
  • docs/topology-status.md
  • polylogue/core/query_identity.py
  • polylogue/storage/sqlite/archive_tiers/ops.py
  • polylogue/storage/sqlite/archive_tiers/ops_write.py
  • polylogue/storage/sqlite/archive_tiers/user.py
  • polylogue/storage/sqlite/migration_runner.py
  • polylogue/storage/sqlite/migrations/user/007_query_objects.sql
  • polylogue/storage/sqlite/query_objects.py
  • polylogue/surfaces/payloads.py
  • tests/unit/core/test_query_identity.py
  • tests/unit/storage/test_durable_migrations.py
  • tests/unit/storage/test_query_objects.py
  • tests/unit/storage/test_query_runs.py

📝 Walkthrough

Walkthrough

This change adds canonical query, query-run, and result-set identities; durable query and result-set persistence; operational query-run telemetry; SearchEnvelope metadata; a user-tier schema migration; and related documentation, topology metadata, and tests.

Changes

Query identity and persistence

Layer / File(s) Summary
Canonical query identity contract
polylogue/core/query_identity.py, docs/query-identity.md, tests/unit/core/test_query_identity.py
Adds deterministic AST canonicalization, SHA-256 query hashing, ObjectRef builders, and tests for normalization, ordering, metadata, and validation.
Durable query objects and migration
polylogue/storage/sqlite/query_objects.py, polylogue/storage/sqlite/migrations/user/007_query_objects.sql, polylogue/storage/sqlite/archive_tiers/user.py, polylogue/storage/sqlite/migration_runner.py, tests/unit/storage/test_query_objects.py, tests/unit/storage/test_durable_migrations.py
Adds query, name, result-set, member, and edge persistence; cycle checks; result-manifest hashing; schema version 7; and saved-query assertion migration.
Query-run telemetry and response metadata
polylogue/storage/sqlite/archive_tiers/ops.py, polylogue/storage/sqlite/archive_tiers/ops_write.py, polylogue/surfaces/payloads.py, docs/openapi/search.yaml, docs/schemas/cli-output/search-envelope.schema.json, tests/unit/storage/test_query_runs.py
Stores bounded query-run records and adds optional query identity, fingerprint, and exactness fields to SearchEnvelope contracts.
Documentation and topology registration
devtools/docs_surface.py, docs/README.md, docs/internals.md, docs/plans/*.yaml, docs/topology-status.md
Registers Query Identity documentation, describes schema version 7, and updates topology projection metadata and generated counts.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant QueryPlan
  participant canonical_query_plan
  participant put_query
  participant queries
  QueryPlan->>canonical_query_plan: planned AST and query metadata
  canonical_query_plan-->>put_query: canonical payload and query hash
  put_query->>queries: idempotently persist canonical query
  queries-->>put_query: stored query object
Loading
✨ 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/fanout/rxdo-substrate

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 added 2 commits July 13, 2026 04:14
Problem: query provenance needs stable shared object references before\nstorage, language, and lifecycle layers can compose around them.\n\nWhat changed:\n- define canonical planned-query hashing and public query object-ref builders\n- document the query/query-run/result-set reference protocol\n- register the protocol document and topology projection\n\nThe ObjectRef kinds were already registered by the prior provenance\nprerequisite; this commit makes their exact identifier shapes and\ncanonicalization contract importable.\n\nRef polylogue-rxdo.2\nRef polylogue-rxdo.3\n\nCo-Authored-By: Codex <[email protected]>
Problem: queries and promoted result relations had no durable identity,\nwhile operational runs could not be inspected independently.\n\nWhat changed:\n- add user.db v7 query, result-set, and planner-edge relations\n- repoint saved-query assertions during the verified durable migration\n- add disposable ops.db query_runs telemetry with bounded sample refs\n- expose additive provenance fields on SearchEnvelope\n\nThe user-v7 migration is additive and no other open user-tier migration\ncandidate was found during batch coordination.\n\nRef polylogue-rxdo.2\nRef polylogue-rxdo.3\n\nCo-Authored-By: Codex <[email protected]>
@Sinity
Sinity force-pushed the feature/fanout/rxdo-substrate branch from f9b2769 to 17a7b1a Compare July 13, 2026 02:23
@Sinity
Sinity merged commit b5e1aac into master Jul 13, 2026
2 of 16 checks passed
@Sinity
Sinity deleted the feature/fanout/rxdo-substrate branch July 13, 2026 02:23
Sinity added a commit that referenced this pull request Jul 13, 2026
…6,2817,2818

th0 (test-harness-2 #2817) and 212.9.1 (fable-demo-2 #2814) fully
satisfied — closed. ra3w/s7ae.8/20d.2 (basetemp-fix #2815, live-performance
continuation #2816) supplementary progress noted on already-open beads.
rxdo.9 (analysis-rigor #2818, program adoption only), rxdo.4 (rxdo-lifecycle
#2812, fuller FINDING implementation but resolve-proof/provenance
projection still deferred), rxdo.2/rxdo.3 (rxdo-substrate #2813, explicitly
incomplete per its own adversarial review) noted with disposition.

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 14, 2026
… provenance (rxdo cluster) (#2899)

## Summary

Advances the rxdo epic's core query/evidence-contract substrate: a real
(non-test-double) production `CanonicalPlanEvaluator`, wired as the
default daemon standing-query evaluator; a lossless predicate round-trip
that makes it possible; `finding:<id>` refs resolving to a queryable
provenance projection; and a declarative improvement-loop registry.

## Problem

Prior PRs (#2813, #2826, #2812, #2791) landed substantial rxdo schema
and contract substrate but explicitly flagged the same real gap in their
own closing notes: `CanonicalPlanEvaluator` had exactly one kind of
implementation anywhere in the repo — hand-rolled fakes inside test
files. `make_default_convergence_stages()` called
`make_standing_query_stage(db_path)` with no evaluator at all, so the
standing-query convergence stage was permanently inert in production.
`record_query_run()` (ops.db telemetry writer) had zero production
callers. `resolve_ref("finding:<id>")` returned the generic
substrate-pending stub even though findings have been real queryable
assertion rows since PR #2812. rxdo.11 asked for a declared loop
registry that didn't exist.

## Solution

- **`polylogue/archive/query/predicate.py`**: `predicate_from_payload()`
— a lossless round trip colocated with each predicate dataclass's own
`to_payload()`. Not a reverse-compiler over free-form text; every branch
inverts one dataclass's own projection.
- **`polylogue/archive/query/production_evaluator.py`**:
`ArchiveCanonicalPlanEvaluator`, the first real evaluator
implementation. Reconstructs a typed predicate from a durable
`query:<hash>` definition's canonical AST, binds field context through
the existing planner-internal `_bind_predicate_context` seam, executes
through the same `SessionFilter` every surface uses, and records a
bounded `ops.db` `query_runs` row (`surface="daemon-internal"`) per
evaluation — a genuine production caller of `record_query_run`. Legacy
protocol-v0 identities and non-session grains fail closed with named
errors.
- **`polylogue/daemon/convergence_stages.py`**:
`make_default_convergence_stages` now injects
`ArchiveCanonicalPlanEvaluator` by default — the named remaining item
from rxdo.5's notes.
- **`polylogue/storage/sqlite/finding_provenance.py`** +
**`polylogue/surfaces/payloads.py`** (`FindingProvenancePayload`):
`compute_finding_provenance()` re-derives a finding's declared
`query_ref`/`result_set_ref`/`baseline_ref`/`current_ref` plus generic
`evidence_refs`, resolves each live, and reports a current/stale/unknown
staleness verdict.
- **`polylogue/api/archive.py`**: `resolve_ref("finding:<id>")`
dispatches to the new resolver instead of the pending-kind stub.
- **`polylogue/insights/improvement_loops.py`**: `LOOP_REGISTRY`
declaring all 13 loop instances from the rxdo.11 design as the 5-tuple
(watch/measure/propose/judge/artifact). Every entry is
`status="horizon"` — no scheduler exists yet, and a dedicated test
asserts `active_loops()` stays empty until one does.

## Non-goals / explicitly deferred

- Cross-surface (CLI/MCP/daemon-web/API) query-run recording parity —
only the daemon-internal evaluator surface records today.
- `from result-set:<id>` / `from query:<hash>` DSL execution wired into
the CLI (rxdo.6) — the evaluator this needed now exists, but CLI/MCP
command-surface wiring is a separate, larger change against
`cli/archive_query.py` (2500+ lines) deferred to a follow-up.
- Cohort resolution (`resolve_cohort` raises `NotImplementedError`).
- rxdo.8 (DB-native analysis recipes): needs a new user-tier schema
migration slot, and polylogue-60i5's corrective contract requires a
declared window + two-consumer stabilization before any new durable
table lands. Not attempted here.
- rxdo.11's two active pilots (L1/L2 executing through a shared
scheduler): blocked on polylogue-37t.17 (L1's read-access log) and an L2
classifier-residue detector, neither of which exist. Only the
declaration registry landed.

## Verification

- `devtools test tests/unit/archive/query/test_production_evaluator.py
tests/unit/archive/query/test_predicate_payload_roundtrip.py
tests/unit/daemon/test_standing_queries_default_evaluator.py
tests/unit/insights/test_improvement_loops.py
tests/unit/api/test_facade_contracts.py
tests/unit/daemon/test_standing_queries.py
tests/unit/archive/query/test_evaluator.py
tests/unit/daemon/test_convergence_stages.py
tests/unit/daemon/test_convergence_final_state.py` — 351 passed, 6
pre-existing failures. Those 6
(`test_archive_tiers_api_timeline_insights_read_index_tier`,
`test_facade_judges_candidate_assertion_in_user_tier`,
`test_archive_tiers_api_session_costs_read_index_tier`,
`test_archive_tiers_api_tag_rollups_read_index_and_user_tiers`,
`test_archive_tiers_api_latency_profiles_read_index_tier`,
`test_archive_tiers_api_archive_coverage_reads_index_tier`) were
independently confirmed present with identical count/names on unmodified
master (verified via a temporary `git stash` + rerun of
`tests/unit/api/test_facade_contracts.py` alone).
- `mypy --strict` over all touched source + test files: clean.
- `ruff check` / `ruff format`: clean.
- `devtools render all --check`: clean (topology projection regenerated
for the 3 new modules).
- `devtools verify --quick`: exit 0 (ran automatically on push via the
pre-push hook).

## Anti-vacuity

`test_evaluate_matches_real_archive_rows` depends on the actual
predicate reconstruction + `SessionFilter` execution: removing
`predicate_from_payload()` or the `SessionFilter.list_summaries()` call
breaks it, since the assertion checks the archive actually filtered by
origin against real ingested rows (not a toy replica).
`test_evaluate_records_a_production_query_run` depends on the
`record_query_run` call: removing it breaks the test, since it reads the
row back from a real `ops.db`.
`test_default_stage_set_evaluates_a_watched_query_without_an_injected_fake`
depends on the `make_default_convergence_stages` wiring: it injects no
fake evaluator at all, only the production one reached through the real
factory function.

Ref polylogue-rxdo.2, polylogue-rxdo.3, polylogue-rxdo.4,
polylogue-rxdo.5, polylogue-rxdo.6, polylogue-rxdo.8, polylogue-rxdo.11

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

## Summary by CodeRabbit

- **New Features**
- Finding references now display detailed provenance, evidence
resolution status, and staleness information.
- Canonical archive queries can be executed with exact session results
and safeguards against self-triggering evaluations.
- Query predicates can be reconstructed reliably from saved
representations.
  - Added a registry for tracking planned improvement loops.

- **Documentation**
- Updated topology documentation and status totals to reflect newly
registered components.

- **Tests**
- Added coverage for finding provenance, query execution, predicate
restoration, and default standing-query behavior.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 18, 2026
…nce (#3093)

## Summary

Stacked on #3090 (needs `report["evidence"]["member_refs"]` added
there).
Represents each claim-vs-evidence report run as durable archive evidence
—
a content-addressed AnalysisDefinition, an AnalysisRun receipt, and
Finding
rows — instead of just a committed `report.json`.

## Problem

`polylogue-rxdo` (It.12/It.13 scope correction) requires that queries
and
analyses be first-party data structures in Polylogue, not a bespoke
devtools
side-pipeline. The rxdo QUERY-evidence core (content-addressed query
identity, canonical-plan evaluator, watched names, result manifests,
durable refs) already landed via #2813/#2826/#2899, and the
`FindingAssertion`/`PublicClaimDeclaration` write kernel + public-claims
projection already landed via #3065 (`polylogue-3tl.16`) — but nothing
had
ever actually written a real `FindingAssertion` into the operator's live
`user.db`; the "3 seeded findings" mentioned in 3tl.16's notes only
exist in
a throwaway temp archive used by `render public-claims`'s
no-`--archive-root`
fallback. This PR adds the smallest finding materialization over the
landed
core, per the addendum's It.13 hard boundary (no metric/pattern/cohort/
experiment definition objects, no registries, no scheduler).

## Solution

`devtools/claim_vs_evidence_evidence.py`:

- **AnalysisDefinition identity** — `build_query_definition()` registers
the
  structured-failure-followup selection (predicate, classification/
  sensitivity scope, `n_min`, handler-class taxonomy, a bumpable
`CLASSIFIER_DEFINITION_VERSION`) as a content-addressed `QueryObject`
via
  `put_query`. Deliberately not a DSL-executable plan — the paired
  next-turn/window-3 lookahead has no predicate-grammar representation —
  but stable provenance identity, matching the "durable identity JSON is
provenance, not source syntax to reverse-compile" doctrine already
stated
  in `convergence_standing_queries.py`.
- **AnalysisRun receipt** — matched `tool_result` refs become a
`ResultSetManifest` (`exactness=capped`, `persistence_class=finding`);
an
`EvaluationReceipt` binds the run to source/user/index tier generations
and the runtime build. Both are content-addressed *including* `now_ms`,
so
  a retried call at the same instant is a safe no-op, while a genuinely
later regeneration correctly records a new run instead of colliding with
  the first.
- **Finding rows** — the headline rate is written as an
  `AssertionKind.FINDING` (`finding_kind="claim-vs-evidence"`, already a
  registered kind) wired to the identities above. `public_claim` stays
  `None` unless the run's own `n_min`/classified-outcome gates are
  satisfied — an unpublishable run still gets an honest private evidence
  record, never a fabricated public rate through the existing
  public-claims projection.
- **Privacy stamp** — reuses the existing
`PublicClaimDeclaration.disclosure`
field (`public` only when publishable, otherwise no declaration at all)
  rather than inventing new privacy/retention machinery; `rxdo.2`'s
  excision/dependency-resolver layer stays explicitly out of scope.

Writes go through `open_daemon_connection` — the same connection helper
`polylogue/daemon/convergence_standing_queries.py` uses for its own
standing-query materialization — via a new opt-in
`--materialize-evidence`
flag on `devtools workspace claim-vs-evidence` (off by default; report
generation stays read-only unless explicitly requested). Not a bare
`sqlite3.connect` against the live `user.db`, and not a generic finding
registry/metric/pattern/cohort/experiment system/scheduler.

## Verification

- `devtools test tests/unit/devtools/test_claim_vs_evidence_evidence.py
  tests/unit/devtools/test_claim_vs_evidence.py
  tests/unit/storage/test_public_claims_projection.py` — 23 passed.
- `mypy --strict` on both touched devtools modules — clean.
- `devtools verify --quick` — green.
- **Live smoke test**: ran `--materialize-evidence` against the actual
live
  archive with the daemon running concurrently (pid confirmed alive
  throughout, no lock contention). Registered 1 `QueryObject`, 1
`ResultSetManifest` (20 members), 2 `EvaluationReceipt`s (two runs a few
  seconds apart), 2 private `FINDING` assertions.
  `list_public_finding_inputs()` correctly returns zero rows — today's
  n=20 result is honestly not publishable, and the projection reflects
  that rather than a fabricated rate.

Ref polylogue-rxdo.13

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

---------

Co-authored-by: Codex <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
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