Skip to content

feat(insights): rxdo.9 measurement substrate primitives - #2888

Merged
Sinity merged 5 commits into
masterfrom
feature/analytics/rigor-measurement-substrate
Jul 14, 2026
Merged

Sinity merged 5 commits into
masterfrom
feature/analytics/rigor-measurement-substrate

Conversation

@Sinity

@Sinity Sinity commented Jul 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

Implements the "measurement primitives" half of the analysis-rigor program
(docs/design/analysis-rigor.md): content-addressed metric/ratio identity,
pre-registration ordering proof, holdout cohort access policy, exactness-gated
uncertainty rendering, standing-query alert budget, and a read-side evidence-
ancestry walker.

Problem

Two real production incidents (the 7.69x Codex cost inflation from an
input-token cache-lane bug, and a stale "376.6B tokens" figure) were both
definition errors computed exactly — there was no mechanism to tell two
differently-defined "cost" numbers apart, no way to prove a claim was
predicted before its confirming query ran, no way to reserve untouched data
for confirmation, and no guard against a naive standing-query alerting
scheme manufacturing false discoveries purely from repeated looks.

Solution

New package polylogue/insights/measurement/:

  • canon.py / metric.py (rxdo.9.1) — metric:<hash> content-addressed
    MetricDefinition (construct, unit, denominator/null policy, required
    enumeration/frame/measurement-authority, confounds, provenance mixing)
    plus an idempotent-by-hash MetricRegistry that rejects a second identity
    bound to the same friendly name.
  • ratio.py (rxdo.9.2) — ratios as derived MetricDefinitions over a
    numerator/denominator component-ref pair, failing closed on
    grain/frame/authority incompatibility. RatioResult always preserves an
    explicit unknown bucket regardless of null_policy — the renderer can
    always answer "% of WHAT".
  • registration.py (rxdo.9.3) — pre-registration ordering proof:
    "registered" only when run_at > registered_at and
    run_epoch > registered_epoch and the metric/query refs are
    unchanged; otherwise an explicit exploratory / exploratory-post-hoc /
    exploratory-definition-drift status. Agents get a provable badge or
    they don't.
  • uncertainty.py (rxdo.9.8) — resolve_uncertainty refuses a bootstrap
    sampling interval for exact/capped enumeration (would misrepresent
    enumeration certainty as inferential uncertainty), while still rendering
    frame-coverage and measurement-authority uncertainty independently of
    exactness — an exact count can carry both without ever getting a CI.
  • alert_budget.py (rxdo.9.5) — evaluate_alert_candidates applies a
    magnitude floor, per-watch cooldown, frame-degradation suppression, and a
    global per-window budget spent largest-deviation-first. Every candidate
    always gets an explicit, receipted decision — nothing is silently
    dropped, and no p-value/significance field exists anywhere in the module.
  • evidence_ancestry.py (rxdo.9.9) — walk_evidence_ancestry traverses
    an injected evidence graph and flags circularity (including a detector
    citing its own prior output), epoch skew, definition-version
    incompatibility, frame-coverage drift, and expired/stale/missing/
    ambiguous/quarantined/private refs, each as its own typed flag with a
    path witness — distinct failures are never flattened into one status.

polylogue/storage/sqlite/holdout_cohorts.py (rxdo.9.4, user.db schema v9,
migration 009_result_set_holdouts.sql): holdout is an access policy
layered on an existing rxdo.2 result_sets manifest, not a second cohort
type. mark_holdout / require_non_holdout_access / record_holdout_access
give exploratory queries a hard refusal by default, a declared confirmation
run an explicit pass plus a visible receipt, and an undeclared access a
permanent contamination marker that no later declared access can clear.

Deferred (each module's docstring says so explicitly)

  • rxdo.6 planner wiring for require_non_holdout_access (the planner
    itself doesn't exist yet).
  • rxdo.5 daemon wiring for AlertBudgetState persistence across restarts
    (to_dict/from_dict exist specifically so this is a thin shim later).
  • The durable finding.v1 / ExperimentDefinition storage that
    registration.py and evidence_ancestry.py would eventually read real
    graphs from — both are pure, storage-agnostic functions today.
  • 9l5.7's statistics registry consuming MetricDefinition as its sole
    identity (this PR is the identity/schema owner per the rxdo.9.1
    authoritative corrective scope; 9l5.7 itself is out of scope here).
  • core/refs.py ObjectRefKind was deliberately left untouched to avoid
    colliding with the parallel rxdo-core (query/evidence contracts) worktree
    editing the same file — metric/ratio refs are plain "<kind>:<hash>"
    strings today, not yet resolved through ObjectRef.parse.
  • rxdo.9.4's AC "reset/excision preserve the declared durability semantics"
    is covered only at the DB layer: migration 009_result_set_holdouts.sql's
    ON DELETE RESTRICT FK makes a raw DELETE of a holdout-marked
    result_sets row raise sqlite3.IntegrityError instead of silently
    dropping the policy (new test
    test_deleting_a_holdout_marked_result_set_is_blocked_by_the_durable_fk).
    No excision/reset mechanism exists for result_sets in this tree at all
    yet, so there is nothing to integration-test beyond that FK proof, and no
    design for how a future excision path (e.g. the separate result_sets
    content, not the polylogue-layg source.db blob-excision cluster which
    doesn't touch this table) should unmark a holdout before deleting it.
    Tracked as open scope on polylogue-rxdo.9.4 rather than closed by this
    PR.

Verification

devtools test tests/unit/insights/measurement/ tests/unit/storage/test_holdout_cohorts.py tests/unit/storage/test_durable_migrations.py
=> 116 passed in 150.93s

(includes the fresh-DDL-vs-migrated-DDL schema fast-forward comparison,
extended to cover the two new holdout tables + index, plus this fix
round's new FK-restrict-on-delete test)

devtools test tests/unit/storage/test_query_objects.py
=> 5 passed (no regression in the rxdo.2 substrate holdout_cohorts.py builds on)
devtools verify --quick
=> exit_code 0

(ruff format/check, mypy --strict, render all --check, topology/layering/
closure-matrix, schema roundtrip, manifests, ci-workflows, doc-commands,
test-infra-currency, test-clock-hygiene, pytest-timeout-overrides,
degrade-loudly)

devtools render topology-projection && devtools render topology-status

regenerated for the new polylogue/insights/measurement/ package.

Not run: the full non-integration suite (devtools verify --all) — the
narrow testmon-affected set above is the relevant surface for this change
and CI runs the heavy suite post-merge per repo convention.

Ref polylogue-rxdo.9.1, polylogue-rxdo.9.2, polylogue-rxdo.9.3,
polylogue-rxdo.9.4, polylogue-rxdo.9.5, polylogue-rxdo.9.8,
polylogue-rxdo.9.9.

@coderabbitai

coderabbitai Bot commented Jul 14, 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: 40 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: 9bb32a38-9aa3-4ecf-b848-da084d567390

📥 Commits

Reviewing files that changed from the base of the PR and between d068d64 and ca4ad98.

📒 Files selected for processing (22)
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/insights/measurement/__init__.py
  • polylogue/insights/measurement/alert_budget.py
  • polylogue/insights/measurement/canon.py
  • polylogue/insights/measurement/evidence_ancestry.py
  • polylogue/insights/measurement/metric.py
  • polylogue/insights/measurement/ratio.py
  • polylogue/insights/measurement/registration.py
  • polylogue/insights/measurement/uncertainty.py
  • polylogue/storage/sqlite/archive_tiers/user.py
  • polylogue/storage/sqlite/holdout_cohorts.py
  • polylogue/storage/sqlite/migrations/user/009_result_set_holdouts.sql
  • tests/unit/insights/measurement/test_alert_budget.py
  • tests/unit/insights/measurement/test_canon.py
  • tests/unit/insights/measurement/test_evidence_ancestry.py
  • tests/unit/insights/measurement/test_metric.py
  • tests/unit/insights/measurement/test_ratio.py
  • tests/unit/insights/measurement/test_registration.py
  • tests/unit/insights/measurement/test_uncertainty.py
  • tests/unit/storage/test_durable_migrations.py
  • tests/unit/storage/test_holdout_cohorts.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/analytics/rigor-measurement-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.

@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: 23f26302b8

ℹ️ 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/insights/measurement/canon.py Resolved
Sinity added a commit that referenced this pull request Jul 14, 2026
Problem: rxdo.9.4's acceptance criterion "reset/excision preserve the
declared durability semantics" was neither implemented, tested, nor
listed in PR #2888's Deferred section, unlike every other genuinely
deferred piece in that PR -- a silent AC gap review flagged as a major.

What changed: add a test proving the migration's existing ON DELETE
RESTRICT FK (result_set_holdout_policies -> result_sets) actually
blocks a raw DELETE of a holdout-marked result set with
sqlite3.IntegrityError, contrasted against an unmarked result set
which deletes cleanly. Document this as the explicit durability floor
in the module docstring: no excision/reset mechanism exists for
result_sets in this tree yet, so this FK-level guarantee is what
"preserve the declared durability semantics" currently means, and a
future excision path must unmark a holdout before deleting it or hit
this same constraint.

Not implemented: an actual excision/reset mechanism for result_sets
(none exists in this tree) or its interaction with a marked holdout --
tracked as open scope on polylogue-rxdo.9.4 rather than silently
closed.

Ref polylogue-rxdo.9.4.
Sinity and others added 3 commits July 14, 2026 16:27
Implements the "measurement primitives" half of the analysis-rigor
program (docs/design/analysis-rigor.md): content-addressed metric/ratio
identity, pre-registration ordering proof, holdout cohort access policy,
exactness-gated uncertainty rendering, standing-query alert budget, and
an evidence-ancestry walker.

Problem: two real production incidents (7.69x Codex cost inflation from
an input-token cache-lane bug, and a stale 376.6B-token figure) were both
DEFINITION errors computed exactly -- there was no mechanism to tell two
differently-defined "cost" numbers apart, no way to prove a claim was
predicted before its confirming query ran, no way to reserve untouched
data for confirmation, and no guard against a naive standing-query
alerting scheme manufacturing false discoveries from repeated looks.

What changed (polylogue/insights/measurement/, new package):
- canon.py / metric.py (rxdo.9.1): metric:<hash> content-addressed
  MetricDefinition (construct, unit, denominator/null policy, required
  enumeration/frame/measurement-authority, confounds, provenance mixing)
  plus an idempotent-by-hash MetricRegistry that rejects a second
  identity for the same friendly name.
- ratio.py (rxdo.9.2): ratios as derived MetricDefinitions over a
  numerator/denominator component-ref pair, failing closed on
  grain/frame/authority incompatibility; RatioResult always preserves an
  explicit unknown bucket regardless of null_policy.
- registration.py (rxdo.9.3): pre-registration ordering proof --
  "registered" only when run_at > registered_at AND run_epoch >
  registered_epoch AND the metric/query refs are unchanged; otherwise an
  explicit exploratory/-post-hoc/-definition-drift status.
- uncertainty.py (rxdo.9.8): resolve_uncertainty refuses a bootstrap
  sampling interval for exact/capped enumeration (would misrepresent
  enumeration certainty), while still rendering frame-coverage and
  measurement-authority uncertainty independently of exactness.
- alert_budget.py (rxdo.9.5): evaluate_alert_candidates applies
  magnitude floor, per-watch cooldown, frame-degradation suppression,
  and a global per-window budget spent largest-deviation-first; every
  candidate always gets an explicit, receipted decision.
- evidence_ancestry.py (rxdo.9.9): walk_evidence_ancestry traverses an
  injected evidence graph and flags circularity (including a detector
  citing its own prior output), epoch skew, definition-version
  incompatibility, frame-coverage drift, and expired/stale/missing/
  ambiguous/quarantined/private refs, each as its own typed flag with a
  path witness -- never flattened into one status.

polylogue/storage/sqlite/holdout_cohorts.py (rxdo.9.4, user.db v9,
migration 009_result_set_holdouts.sql): holdout is an access POLICY
layered on an existing rxdo.2 result_sets manifest, not a second cohort
type. mark_holdout/require_non_holdout_access/record_holdout_access give
exploratory queries a hard refusal by default, a declared confirmation
run an explicit pass plus a visible receipt, and an undeclared access a
permanent contamination marker that no later declared access can clear.

Deferred / not in this PR (each module's docstring says so explicitly):
rxdo.6 planner wiring for require_non_holdout_access; rxdo.5 daemon
wiring for AlertBudgetState persistence; the durable finding.v1 /
ExperimentDefinition storage that registration.py and
evidence_ancestry.py would eventually read from; 9l5.7's statistics
registry consuming MetricDefinition. core/refs.py ObjectRefKind was
deliberately left untouched to avoid colliding with the parallel
rxdo-core (query/evidence contracts) worktree on the same file --
metric/ratio refs are plain "<kind>:<hash>" strings today, not yet
resolved through ObjectRef.parse.

Verification:
- devtools test tests/unit/insights/measurement/ tests/unit/storage/test_holdout_cohorts.py tests/unit/storage/test_durable_migrations.py
  -> 115 passed in 129.76s (includes the fresh-DDL-vs-migrated-DDL
  schema fast-forward comparison for the new holdout tables).
- devtools test tests/unit/storage/test_query_objects.py -> 5 passed
  (no regression in the rxdo.2 substrate holdout_cohorts.py builds on).
- devtools verify --quick -> exit 0 (ruff format/check, mypy --strict,
  render all --check, topology/layering/closure-matrix, schema
  roundtrip, manifests, ci-workflows, doc-commands, test-infra-currency,
  test-clock-hygiene, pytest-timeout-overrides, degrade-loudly).
- devtools render topology-projection && devtools render topology-status
  regenerated for the new polylogue/insights/measurement/ package.

Ref polylogue-rxdo.9.1, polylogue-rxdo.9.2, polylogue-rxdo.9.3,
polylogue-rxdo.9.4, polylogue-rxdo.9.5, polylogue-rxdo.9.8,
polylogue-rxdo.9.9.

Co-Authored-By: Claude <[email protected]>
Problem: rxdo.9.4's acceptance criterion "reset/excision preserve the
declared durability semantics" was neither implemented, tested, nor
listed in PR #2888's Deferred section, unlike every other genuinely
deferred piece in that PR -- a silent AC gap review flagged as a major.

What changed: add a test proving the migration's existing ON DELETE
RESTRICT FK (result_set_holdout_policies -> result_sets) actually
blocks a raw DELETE of a holdout-marked result set with
sqlite3.IntegrityError, contrasted against an unmarked result set
which deletes cleanly. Document this as the explicit durability floor
in the module docstring: no excision/reset mechanism exists for
result_sets in this tree yet, so this FK-level guarantee is what
"preserve the declared durability semantics" currently means, and a
future excision path must unmark a holdout before deleting it or hit
this same constraint.

Not implemented: an actual excision/reset mechanism for result_sets
(none exists in this tree) or its interaction with a marked holdout --
tracked as open scope on polylogue-rxdo.9.4 rather than silently
closed.

Ref polylogue-rxdo.9.4.
Problem: two reviewer-flagged P2 gaps in the rxdo.9.1 metric:<hash>
identity mechanism, unfixed after being raised on this branch:

1. metric.py canonical_payload() serialized measurement_authority as
   list(self.measurement_authority), preserving construction-order,
   while is_compatible_with() treats the same field as an
   order-independent set. Two definitions built with
   ("provider-reported", "heuristic") vs ("heuristic", "provider-reported")
   describe the same measurement envelope but hashed to different
   metric:<hash> refs -- falsifying the rxdo.9.1 AC that an equivalent
   second identity is impossible/rejected.

2. canon.py's canonicalize() passed string scalars through unchanged
   before hash_payload() hashed them byte-for-byte. hash_payload's own
   docstring says it deliberately does NOT NFC-normalize and expects
   callers to; canon.py's module docstring claims parity with the
   rxdo.2 query:<hash> canonicalizer (core/query_identity.py), which
   DOES NFC-normalize every string and dict key -- the claimed parity
   was false, so two definitions differing only in Unicode
   normalization form minted different refs.

What changed:
- metric.py: canonical_payload() now sorts measurement_authority
  before hashing, matching the order-independent semantics
  is_compatible_with() already assumes.
- canon.py: canonicalize() now NFC-normalizes str scalars and mapping
  keys, matching core/query_identity.py's _nfc/_canonical_value
  pattern the module docstring already claimed to follow.
- metric.py: MetricRegistry.register()'s collision guard now compares
  canonical_payload() instead of dataclass field equality. This was a
  second-order bug the measurement_authority fix exposed: two
  definitions can now share a ref while differing in raw tuple
  construction order, which dataclass `!=` flagged as a false
  "hash collision", incorrectly rejecting legitimate re-registration
  under the same friendly name.

Verification:
- devtools test tests/unit/insights/measurement/ tests/unit/storage/test_holdout_cohorts.py tests/unit/storage/test_durable_migrations.py
  -> 121 passed in 124.44s (was 116; +5 new tests covering order/NFC
  invariance and the registry collision-guard fix)
- devtools verify --quick -> exit 0

Ref polylogue-rxdo.9.1

Co-Authored-By: Claude <[email protected]>
@Sinity
Sinity force-pushed the feature/analytics/rigor-measurement-substrate branch from 5f7ae8d to 528f94c Compare July 14, 2026 14:30
Sinity added 2 commits July 14, 2026 16:30
Problem: rebasing feature/analytics/rigor-measurement-substrate onto
origin/master picked up master's hermes/security topology changes,
leaving the docs/plans/topology-target.yaml and docs/topology-status.md
conflict resolution stale relative to the new base.

What changed: regenerated both generated surfaces via
`devtools render topology-projection && devtools render topology-status`
so they reflect this branch's polylogue/insights/measurement/ package
composed with master's latest module set.

Verification: devtools verify --quick => exit_code 0.
# Conflicts:
#	docs/plans/topology-target.yaml
#	docs/topology-status.md
@Sinity
Sinity merged commit c5b36d3 into master Jul 14, 2026
2 checks passed
@Sinity
Sinity deleted the feature/analytics/rigor-measurement-substrate branch July 14, 2026 18:31
Sinity added a commit that referenced this pull request Aug 5, 2026
## Summary

Restore and wire the three modules identified by polylogue-ic5i. Git
history, Bead intent, and the current architecture all show these as
intended capabilities rather than positively unwanted code. No archive
migration or lifecycle work is included.

## Problem

PR #3390 removed `storage/sqlite/holdout_cohorts.py`,
`insights/fable_packet.py`, and `storage/block_anchor.py` because they
had no production callers. Their prior design records show incomplete
integration or an adopted contract, so deletion would remove desired
behavior. The holdout policy was especially unsafe as an uncalled guard
could not protect any route.

## Solution

- `storage/sqlite/holdout_cohorts.py`: RESTORE + WIRE. Bead
`polylogue-rxdo.9.4` and PR #2888 establish the analysis-integrity
policy. `DurableRefResolver._retained_result` now applies the guard
before reading result-set members, and the registered MCP
reference-query route reaches that resolver. Exploratory reads fail
closed for held-out result sets; explicit confirmation remains available
to confirmation callers.
- `insights/fable_packet.py`: RESTORE + WIRE. Bead `polylogue-212.9.1`
and PR #2814 establish the archive-backed cold-regeneration adapter.
`Polylogue.regenerate_private_fable_packet` exposes it through the
existing async API facade and operation-parity surface, including real
delegation and annotation reads.
- `storage/block_anchor.py`: RESTORE + WIRE. Bead `polylogue-svfj` and
PR #2588 establish the content-hash citation-anchor contract.
`Polylogue.resolve_ref` now recognizes the textual anchor form and
resolves it through the existing archive read route, returning a typed
block-anchor payload.

No module was deleted. The deferred `relocated_lineage` and
`quarantined` anchor states remain unchanged because this task does not
establish their production semantics.

## Holdout enforcement and anti-vacuity

The guard is enforced in the production evaluation path, before the sole
`get_result_set_members()` call.
`tests/unit/archive/query/test_evaluator.py::test_retained_holdout_result_set_fails_closed_before_members_are_read`
proves the resolver ordering.
`tests/unit/mcp/test_reference_query_pipeline.py::test_mcp_query_refuses_an_exploratory_read_of_a_holdout_result_set`
seeds durable result-set data and exercises the registered MCP query
handler. Removing `require_non_holdout_access` changes that route from a
typed refusal to a successful member read, so the tests do not merely
assert a helper or a test-only registry.

The Fable facade test uses a real temporary archive with persisted
delegations and labels. The block-anchor test resolves an actual stored
block through `run_archive_read` and checks its content hash.

## Verification

Focused real-route tests:

```text
direnv exec . devtools test tests/unit/archive/query/test_evaluator.py tests/unit/mcp/test_reference_query_pipeline.py tests/unit/api/test_facade_contracts.py tests/unit/insights/test_fable_packet.py tests/unit/storage/test_block_anchor.py tests/unit/storage/test_holdout_cohorts.py
337 passed, 4 warnings in 34.05s
```

Quick gate on the rebased head:

```text
direnv exec . devtools verify --quick
exit_code: 0
run_id: 20260805T075357Z-quick-1683451-664ef79b
```

`devtools verify --all` and the integration suite were not run. The
focused suite covers the changed production routes and the quick gate
covers formatting, typing, generated surfaces, layering, and policy
checks.

## Review notes

An independent adversarial review traced the MCP route to
`DurableRefResolver` and found one legitimate gap: the initial Fable
facade test covered only an empty archive. Commit `0813d4415` adds a
non-empty persisted delegation and label case, then the focused suite
and quick gate were rerun on the rebased head. A nested cold review
process later hit the checkout guard because it bypassed `direnv`; it
emitted no additional actionable finding.

---------

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

Sinity commented Sep 30, 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.

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.

1 participant