From e7dd2bc174d49e1720f378ade245ebaffd0c93cb Mon Sep 17 00:00:00 2001 From: Timothy Wayne Gregg Date: Tue, 17 Nov 2026 20:49:05 -0500 Subject: [PATCH 1/2] Measure authored research-domain workloads and propose reference placement Signed-off-by: Timothy Wayne Gregg --- docs/adr/0001_research_domain_storage.md | 39 ++ docs/research_domain_workloads.md | 38 ++ tests/test_research_domain_workloads.py | 203 +++++++++ trace_gc/cli.py | 9 + trace_gc/retrieval/domain_index.py | 6 +- trace_gc/retrieval/domains.py | 30 +- trace_gc/retrieval/security.py | 8 + trace_gc/retrieval/service.py | 5 + trace_gc/retrieval/store.py | 19 +- trace_gc/retrieval/strategies.py | 10 +- trace_gc/retrieval/telemetry.py | 101 +++++ trace_gc/retrieval/workloads.py | 551 +++++++++++++++++++++++ 12 files changed, 1006 insertions(+), 13 deletions(-) create mode 100644 docs/adr/0001_research_domain_storage.md create mode 100644 docs/research_domain_workloads.md create mode 100644 tests/test_research_domain_workloads.py create mode 100644 trace_gc/retrieval/telemetry.py create mode 100644 trace_gc/retrieval/workloads.py diff --git a/docs/adr/0001_research_domain_storage.md b/docs/adr/0001_research_domain_storage.md new file mode 100644 index 0000000..bbd3e7c --- /dev/null +++ b/docs/adr/0001_research_domain_storage.md @@ -0,0 +1,39 @@ +# ADR 0001 — Shared logical domain views; deployment placement decision pending + +**Status** Proposed for the reference design. Deployment placement awaits owner review and representative evidence. Refs #10, #11, and epic #4. + +**Decision owner** Pending. An authorized deployment and data owner must accept or replace this decision after the representative-input gate. + +## Context + +A research domain is mutable, multi-label search metadata. It is neither a tenant grant, a relation endpoint type, an ontology, nor a graph community. Identity, full graph constraints, accepted publication, immutable source/evidence provenance and historical audit remain graph-wide within one trust/transaction boundary. A source can change domains, belong to several domains, or remain unclassified. Required identity and refutation closure crosses topical labels. + +The reference work provides versioned classification operations inside the existing publication transaction and rebuildable indexes over its accepted snapshots. The live initiative has not supplied a selected deployment backend/owner, representative independently labeled data, isolation requirements, or agreed workload/SLOs. The measured fixture run is explicitly synthetic, small and single-host. It is not evidence of a production capacity limit or of a distribution benefit. + +## Provisional choice + +**Retain one accepted graph authority per trust/transaction boundary and shared logical research-domain views in the reference implementation.** Keep the domain index disposable and derived; use stable source, evidence, entity, assertion, assignment and taxonomy identities independent of topical routing. Do not split databases by research-domain label. This choice preserves the specified semantics without presupposing a production database product or deployment readiness. + +The deployment owner must later choose the physical implementation from the preregistered workload and hard isolation needs. This ADR does not convert SQLite-reference into the deployment backend. + +## Alternatives and decision triggers + +| Option | Current disposition | Evidence needed / consequence | +|---|---|---| +| Shared logical graph in one authority | Reference choice | Qualify the selected backend's consistent reads, ACL enforcement, journal, restore and source epochs on representative workloads. Measure full graph validation and index/audit costs, not just lookup latency. | +| Dedicated storage for a hard trust/residency boundary | Conditional; not selected | An actual legal, tenancy, administrative or residency requirement with an owner. Dedicated storage is keyed to that boundary, not topical labels. Explicitly govern any authorized cross-boundary references and evidence transfer. | +| Measured physical sharding | Deferred; no implementation issue justified | A reproducible representative bottleneck after reasonable query/index/cache work, a measured benefit, and explicit routing/consistency/transaction costs. Synthetic fixtures and arbitrary node/edge thresholds cannot satisfy this trigger. | + +Revisit when the backend and owner are selected; hard isolation requirements change; measured SLO or resource-pressure failures occur on representative peak/high-degree/churn workloads; or the accepted workload materially changes. A numeric node-count threshold is intentionally absent. + +## Requirements before any physical split + +The separately scoped implementation issue must define stable globally resolvable IDs and unchanged immutable source/evidence hashes; authenticated provenance and cross-partition identity/refutation links; a versioned routing map and routing epoch; a consistent graph/classification snapshot identity; present source-epoch and revocation propagation before every returned result; fail-closed timeouts, cancellation and unavailable-history behavior; idempotent publication through one authority; atomic visibility of graph-wide constraints, journal and projections; and consistent backup/restore including journal, trust-enrollment and revocation state. + +A participant-local success cannot be a graph-wide commit. A search index cannot become another authority. Do not weaken publication constraints to avoid cross-partition validation, silently drop contradictory evidence, reinterpret current ACLs on historical reads, or rewrite identities when moving labels. Specify the actual commit/recovery protocol and test partial failures, not just the desired behavior. Any proposed dedicated or sharded layout requires its own security and operational evidence. + +## Evidence and limitations + +`trace_gc.retrieval.workloads` and `docs/research_domain_workloads.md` define reproducible measurements: latency p50/p95/p99, cross-domain transitions and writes, degree skew, ACL/audit/index cost, cache churn, source withdrawal and paired retrieval quality. The reproducible reference command exercises measurement plumbing and concurrent compare-and-swap, not a representative workload. Low sample counts and fixture-authored labels prohibit production-performance or accuracy conclusions. No sharding implementation issue was created because the required justification is absent. + +#10 remains open until benchmark inputs, representative results, owner/SLOs and an accepted ADR are available. #11 and #4 remain open until actual deployment acceptance passes independently of these reference tests. diff --git a/docs/research_domain_workloads.md b/docs/research_domain_workloads.md new file mode 100644 index 0000000..dac8f33 --- /dev/null +++ b/docs/research_domain_workloads.md @@ -0,0 +1,38 @@ +# Domain workload measurement protocol + +Refs #10. This is instrumentation and a reproducible **synthetic reference smoke**, not representative data, an independent-label experiment, a deployment SLO result, or a sharding justification. + +## Reproduce the reference run + +```sh +python -m trace_gc domain-workload --output domain-workload.json --repetitions 3 --workers 2 +python -m unittest discover -s tests -p 'test_research_domain_workloads.py' -v +``` + +The command runs eight paired in-memory query cases per worker/repetition, then an authored scope denial and a separate disposable SQLite-reference publication/read phase. Query cases cover lexical/vector contradiction retrieval, paths and communities in scoped and unscoped forms. The SQLite phase measures append-only migration, multi-label assignment/reclassification, idempotent retries, read-index validation, cache reuse/churn, current withdrawal on historical reads, and two competing connections at the same graph version. Exactly one concurrent writer must commit; the stale rejection is not counted as a graph write. + +The in-memory workers are same-process threads over copies of one immutable reference snapshot. They are not deployment-like clients, distributed replicas, or independent accepted graph authorities. No private corpus, trained model, provider credential, application deployment trust root, or production database is used. + +## Metrics and limitations + +`WorkloadRecorder`, `QueryCase`, `run_query_workload`, `measure_query` and `measure_publication` are reusable with an application's representative inputs and existing trusted services. The recorder does **not** create ACL grants or approve a publication. The publication wrapper requires ordinary signed preflight/authorization receipts. It reserves bounded telemetry capacity before execution, so capacity exhaustion cannot happen only after a successful write. + +Latency uses `perf_counter_ns`; percentiles use nearest rank and always carry sample counts. Queries include consistent authority reads, ACL checks, candidate generation, canonical revalidation and cache handling. Write latency measures the trusted publish/commit call, excluding caller plan preparation/signing. Committed, replayed and rejected publication samples remain distinguishable. + +ACL calls are counted by guard; only outermost nested guard wall time is timed, preventing double accounting. Measurement contexts are isolated across threads and reset on exceptions. These are opt-in, process-local observations, not changes to scientific records, snapshot identity or permissions. Instrumentation itself has overhead; no measured production-speed claim is made. + +Domain transitions count executed path/community/required-closure hops. A transition may change membership while retaining an overlapping domain; disjoint domain hops and unclassified hops are separate counters. Revalidation may repeat a transition. These are not unique graph edges, network messages, remote transactions, or cross-shard RPCs. A cross-domain write means the union of exact pre/post source assignments touched by a signed plan has multiple taxonomy/domain pairs; it is a metadata-workload observation, not proof that storage crossed a partition. + +Topology reports incident active original-assertion degrees, quantiles, Gini, and top-one-percent degree share. A test compares equal-sized star and chain graphs to ensure node count alone does not erase high-degree skew. Those test graphs are not a representative performance workload. The default small corpus does not exercise a deployment's high-degree tail. + +Index observations include serialized source-row bytes, elapsed time and counts of source and membership rows. The harness measures explicit index materialization and rebuild separately through the phase-owned adapter operations. Retrieval remains read-only and distinguishes projection-only reads from verification of a persisted index. Full authority-audit time and SQLite `dbstat` B-tree bytes are also recorded when available. Database/WAL byte counts are not working-set measurements. Linux RSS observations are process-wide snapshots including the harness and imported modules, not an isolated query's allocation or a deployment memory requirement. + +Cache hits/misses, invalidated entries and capacity evictions are distinct. A deliberately small cache exercises churn, not a recommended production cache size. Paired quality compares only the same case ID with/without scope; unlabeled path/community quality is reported as unavailable, not perfect. The lexical/vector fixture contains an explicitly authored cross-domain refutation: preserving it is a conformance check, not evidence of real scientific retrieval accuracy. The report tracks whether a structured conflict item carries both assertion IDs separately from whether both evidence IDs were returned. Current withdrawal is tested separately with forbidden-source expectations. + +## Representative-input gate + +Before running a placement study, the actual owner must preregister corpus/snapshot hashes, reviewed taxonomy and assignments, independently produced evidence/contradiction labels, query/write mixture, tenant/ACL distribution, source churn, high-degree tail, cache working set, expected concurrency, hardware/backend version, isolation/residency requirements, and latency/availability/recovery SLOs. Use the same authority snapshots, current revocation rules and labeled cases for every candidate storage option. Report misses, timeouts and rejected writes; do not report only successes. Freeze the protocol and train/tune/test split before inspecting outcomes. + +An input manifest may identify `REPRESENTATIVE_CANDIDATE`, but that string or an owner name cannot mint representativeness, independent labels, or an acceptance receipt. The harness deliberately reports `MEASURED_NOT_QUALIFIED` and leaves qualification to explicit external review and the deployment gates. Store operational telemetry behind administrator access controls: even aggregate graph cardinality, query categories and hashes can be sensitive. Do not publish a representative corpus or telemetry without its owner's authorization. + +The command stores individual per-operation measurements in the requested path. Keep detailed receipts in approved operational storage and publish only authorized aggregates. The default run is expected to record 56 query observations and 10 publication attempts, including four idempotent replays and one stale-version rejection. The fixed timestamp for authored queries pins the reference protocol. Timings and ephemeral receipt hashes can differ between runs. The September synthetic diagnostic recorded on [#10](https://github.com/Jev-Engineering/jraphyte/issues/10) used a separate protocol. See [ADR 0001](adr/0001_research_domain_storage.md) for the proposed reference choice and external decision gate. diff --git a/tests/test_research_domain_workloads.py b/tests/test_research_domain_workloads.py new file mode 100644 index 0000000..62077a5 --- /dev/null +++ b/tests/test_research_domain_workloads.py @@ -0,0 +1,203 @@ +"""Measured workload plumbing, never representative labels or a sharding claim.""" +from concurrent.futures import ThreadPoolExecutor +from copy import deepcopy +import json +from pathlib import Path +import tempfile +import threading +import unittest +from unittest.mock import Mock + +from trace_gc.canonical import digest +from trace_gc.domain_publication import migration_operation +from trace_gc.errors import ContractError +from trace_gc.retrieval.contracts import query, RetrievalBudget +from trace_gc.retrieval.domains import research_domain_scope +from trace_gc.retrieval.fixtures import domain_corpus, SCOPE +from trace_gc.retrieval.security import AccessFilter +from trace_gc.retrieval.telemetry import active, measure_retrieval, measured_acl, domain_hop +from trace_gc.retrieval.workloads import (QueryCase, WorkloadRecorder, percentiles, topology, measure_query, + measure_publication, run_reference_domain_workload) +from test_research_domain_transactions import DomainFixture + + +def recorder(**changes): + manifest = {"data_kind": "SYNTHETIC", "corpus_hash": "a" * 64, "labels_hash": "b" * 64, + "protocol_id": "synthetic-workload-test-v1"} + return WorkloadRecorder(input_manifest=manifest, **changes) + + +class WorkloadMetricTests(unittest.TestCase): + def test_percentiles_are_nearest_rank_with_actual_sample_count(self): + self.assertEqual(percentiles([5, 1, 4, 3, 2]), {"count": 5, "p50": 3, "p95": 5, "p99": 5, "maximum": 5}) + self.assertEqual(percentiles([])["p99"], None) + self.assertEqual(percentiles([7])["p50"], 7) + + def test_invalid_measurements_do_not_produce_plausible_percentiles(self): + for values in ([True], [-1], [float("nan")], [float("inf")]): + with self.subTest(values=values), self.assertRaises(ContractError): + percentiles(values) + + def test_equal_node_counts_can_have_different_high_degree_skew(self): + def graph(pairs): + return {"nodes": {str(i): "Entity" for i in range(101)}, + "assertions": {str(i): {"active": True, "assertion": {"subject": str(a), "object": str(b)}} + for i, (a, b) in enumerate(pairs)}} + star = topology(graph([(0, i) for i in range(1, 101)])) + chain = topology(graph([(i - 1, i) for i in range(1, 101)])) + self.assertEqual(star["nodes"], chain["nodes"]) + self.assertEqual(star["active_original_assertions"], chain["active_original_assertions"]) + self.assertEqual(star["degree"]["maximum"], 100) + self.assertEqual(chain["degree"]["maximum"], 2) + self.assertGreater(star["degree_gini"], chain["degree_gini"]) + self.assertNotIn("shard", json.dumps(star)) + + def test_nested_acl_calls_count_but_do_not_double_time(self): + @measured_acl("inner") + def inner(): + return True + @measured_acl("outer") + def outer(): + return inner() + with measure_retrieval() as measurement: + self.assertTrue(outer()) + self.assertEqual(dict(measurement.acl_calls), {"outer": 1, "inner": 1}) + self.assertGreater(measurement.acl_elapsed_ns, 0) + self.assertEqual(measurement._acl_depth, 0) + self.assertFalse(active()) + + def test_acl_exceptions_do_not_leak_measurement_context(self): + @measured_acl("reject") + def reject(): + raise ContractError("ACCESS_DENIED", "test") + with self.assertRaises(ContractError), measure_retrieval() as measurement: + reject() + self.assertEqual(measurement.acl_calls["reject"], 1) + self.assertEqual(measurement._acl_depth, 0) + self.assertFalse(active()) + + def test_concurrent_measurements_are_isolated(self): + barrier = threading.Barrier(2) + @measured_acl("check") + def check(): + return True + def work(count): + with measure_retrieval() as measurement: + barrier.wait(timeout=5) + for _ in range(count): + check() + return dict(measurement.acl_calls) + with ThreadPoolExecutor(max_workers=2) as pool: + self.assertEqual(list(pool.map(work, [3, 7])), [{"check": 3}, {"check": 7}]) + + def test_cross_domain_unknown_and_overlapping_transitions_are_distinct(self): + with measure_retrieval() as m: + domain_hop({("tax", "bio")}, {("tax", "physics")}, channel="path") + domain_hop({("tax", "bio")}, {("tax", "bio"), ("tax", "chem")}, channel="path") + domain_hop(set(), {("tax", "bio")}, channel="path") + self.assertEqual(m.domain_hops["path:transitions"], 3) + self.assertEqual(m.domain_hops["path:disjoint_domain_transitions"], 1) + self.assertEqual(m.domain_hops["path:membership_changing_transitions"], 2) + self.assertEqual(m.domain_hops["path:unclassified_transitions"], 1) + + def test_capacity_is_reserved_before_a_publication_can_happen(self): + r = recorder(maximum_samples=1) + r.append({"kind": "QUERY", "operation": "occupied", "outcome": "REFUSED", "elapsed_ms": 0}) + service = Mock() + with self.assertRaises(ContractError) as caught: + measure_publication(service, Mock(), "plan", r, authorization={}, preflight={}) + self.assertEqual(caught.exception.code, "WORKLOAD_LIMIT") + service.publish.assert_not_called() + + def test_representative_candidate_metadata_does_not_mint_qualification(self): + r = WorkloadRecorder(input_manifest={"data_kind": "REPRESENTATIVE_CANDIDATE", "corpus_hash": "a" * 64, + "labels_hash": "b" * 64, "protocol_id": "unsigned-input-metadata", "owner": "claimed-owner"}) + self.assertEqual(r.report()["qualification"]["representativeness"], "NOT_ESTABLISHED") + self.assertEqual(r.report()["qualification"]["production_backend"], "NOT_QUALIFIED") + + def test_recorder_rejects_unbound_inputs(self): + with self.assertRaises(ContractError): + WorkloadRecorder(input_manifest={"data_kind": "SYNTHETIC", "corpus_hash": "not-a-hash", "labels_hash": "b" * 64, + "protocol_id": "test"}) + + +class WorkloadExecutionTests(unittest.TestCase): + def test_actual_query_measurements_preserve_retrieval_and_do_not_log_source_text(self): + f = domain_corpus() + c, retriever = f["catalog"], f["retriever"] + scope = research_domain_scope(c, f["taxonomy_id"], ["research:biology"]) + request = query(requesting_component="downstream-search", security_scope=SCOPE, strategies=["LEXICAL"], + text="improves", research_domain_scope=scope, budget=RetrievalBudget(maximum_tokens=100000, maximum_latency_ms=20000)) + reference = c.get(c.get(retriever.retrieve(request))["graph_context_id"])["items"] + r = recorder() + required = frozenset({f["evidence"]["e-support"], f["evidence"]["e-refute"]}) + result_id = measure_query(retriever, QueryCase("public-case-id", request, required, (required,)), r) + self.assertEqual(c.get(c.get(result_id)["graph_context_id"])["items"], reference) + sample = r.report()["samples"][0] + self.assertEqual(sample["quality"]["evidence_recall"], 1) + self.assertEqual(sample["quality"]["missed_contradiction_pairs"], 0) + self.assertGreater(sample["measurements"]["acl_calls"]["source"], 0) + self.assertGreater(sample["measurements"]["acl_elapsed_ms"], 0) + self.assertNotIn(c.get(f["evidence"]["e-support"])["quote"], json.dumps(sample)) + self.assertEqual(sample["cache_delta"]["hits"], 1) + + def test_unsigned_publication_fails_and_is_counted_as_rejected_not_written(self): + with tempfile.TemporaryDirectory() as directory: + f = DomainFixture(directory) + try: + pid = f.plan([migration_operation(operation_id="initialize", reason="test")]) + auth, preflight = f.approvals(pid) + auth["signature"] = "AA==" + r = recorder() + before = f.backend.state() + with self.assertRaises(ContractError): + measure_publication(f.service, f.catalog, pid, r, authorization=auth, preflight=preflight) + self.assertEqual(f.backend.state(), before) + self.assertEqual(r.report()["writes"], {"committed": 0, "cross_domain_batches": 0, + "cross_domain_batch_rate": None, "replayed": 0, "rejected": 1}) + finally: + f.close() + + def test_synthetic_smoke_runs_real_reference_writes_indexes_churn_and_cas(self): + report = run_reference_domain_workload(repetitions=1, workers=1) + self.assertEqual(report["input_manifest"]["data_kind"], "SYNTHETIC") + self.assertEqual(report["status"], "MEASURED_NOT_QUALIFIED") + self.assertEqual(report["sample_count"], 26) + # The integrated protocol includes rejected requests and exact identity + # implementation pins; neither prior branch's coverage may be discarded. + from trace_gc.canonical import bytes_digest + import trace_gc + package = Path(trace_gc.__file__).resolve().parent # works from a checkout or an installed wheel + self.assertEqual(report["implementation_hashes"]["items.py"], + bytes_digest((package / "retrieval/items.py").read_bytes())) + self.assertEqual(report["implementation_hashes"]["../constraints.py"], + bytes_digest((package / "constraints.py").read_bytes())) + self.assertEqual(report["query_outcomes"], {"completed": 15, "rejected_or_error": 1}) + self.assertEqual(report["telemetry_coverage"], {"queries": 16, "measured_queries": 16, "unmeasured_queries": 0}) + self.assertEqual(report["acl_elapsed_ms"]["count"], 16) + denied = next(row for row in report["samples"] if row.get("case_id") == "acl-scope-rejected") + self.assertEqual(denied["outcome"], "SECURITY_SCOPE") + self.assertFalse(denied["completed"]) + self.assertIsNone(denied["quality"]) + self.assertEqual(report["writes"]["committed"], 5) + self.assertEqual(report["writes"]["replayed"], 4) + self.assertEqual(report["writes"]["rejected"], 1) + self.assertCountEqual(report["concurrent_write_outcomes"], ["COMMITTED", "STALE_GRAPH_VERSION"]) + self.assertEqual(report["index_validation_ms"]["count"], 7) + self.assertEqual(report["index_latency_ms_by_mode"]["VERIFIED"]["count"], 7) + self.assertEqual(report["cold_projection"]["mode"], "PROJECTED") + self.assertEqual([row["mode"] for row in report["index_preparations"]], + ["REBUILT", "MATERIALIZED", "MATERIALIZED"]) + self.assertTrue(all(row["logical_source_row_bytes"] > 0 for row in report["index_preparations"])) + self.assertEqual(report["publication_domain_coverage"], {"committed": 5, "classified": 5}) + self.assertGreater(report["cache"]["hits"], 0) + self.assertGreater(report["cache"]["invalidations"], 0) + self.assertGreater(report["domain_hops"]["path:transitions"], 0) + self.assertEqual(report["quality"]["scoped"]["forbidden_sources_returned"], 0) + self.assertEqual(report["paired_comparison"]["lexical-conflict"]["scoped"]["missed_contradiction_pairs"], 0) + lexical = report["paired_comparison"]["lexical-conflict"] + self.assertIsNotNone(lexical["unscoped"]["missing_structured_conflicts"]) + self.assertIsNotNone(lexical["scoped"]["missing_structured_conflicts"]) + self.assertIsNone(report["paired_comparison"]["path"]["scoped"]["missing_structured_conflicts"]) + self.assertEqual(report["production_graph_writes"], 0) + self.assertEqual(report["provider_calls"], 0) diff --git a/trace_gc/cli.py b/trace_gc/cli.py index 7037df5..a53cd53 100644 --- a/trace_gc/cli.py +++ b/trace_gc/cli.py @@ -43,6 +43,10 @@ def parser() -> argparse.ArgumentParser: gd.add_argument("--output",type=Path,default=Path("trace-gc-graphrag-demo")) gb=sub.add_parser("graphrag-benchmark",help="Run the synthetic retrieval/pipeline ablations; not a real-model accuracy evaluation") gb.add_argument("--output",type=Path,default=Path("trace-gc-graphrag-benchmark")) + dw=sub.add_parser("domain-workload",help="Measure authored synthetic domain workloads in disposable reference stores") + dw.add_argument("--output",type=Path,required=True) + dw.add_argument("--repetitions",type=int,default=3) + dw.add_argument("--workers",type=int,default=2) c=sub.add_parser("canonical",help="Generate a TRACE-C14N-1 hash and byte vector") c.add_argument("input",type=Path) e=sub.add_parser("evaluate-labels",help="Calculate an UNSIGNED qualification artifact from independent labels") @@ -82,6 +86,11 @@ def main(argv: list[str] | None=None) -> int: report=run_benchmark(args.output) result={k:report[k] for k in ("status","cases","runs","provider_calls","production_graph_writes","interpretation")} result["output"]=str(args.output) + elif args.command=="domain-workload": + from .retrieval.workloads import run_reference_domain_workload + report=run_reference_domain_workload(args.output,repetitions=args.repetitions,workers=args.workers) + result={k:report[k] for k in ("status","sample_count","query_latency_ms","publication_latency_ms","writes","placement_decision")} + result["output"]=str(args.output) elif args.command=="canonical": value=load(args.input);result={"profile":"TRACE-C14N-1","sha256":digest(value),"bytes_hex":canonical_bytes(value).hex()} elif args.command=="evaluate-labels": diff --git a/trace_gc/retrieval/domain_index.py b/trace_gc/retrieval/domain_index.py index 92f71e5..3b464ef 100644 --- a/trace_gc/retrieval/domain_index.py +++ b/trace_gc/retrieval/domain_index.py @@ -97,12 +97,14 @@ def membership(rows: dict[str, dict[str, Any]]) -> list[tuple[str, str, str]]: for source_id, row in rows.items() for domain in (row["domain_ids"] or [""])) def read(self, catalog: Catalog, snapshot_id: str, *, rebuild: bool = False, - persist: bool = True) -> dict[str, dict[str, Any]]: + persist: bool = True, metrics: dict[str, str] | None = None) -> dict[str, dict[str, Any]]: """`persist=False` verifies an existing entry but never creates or deletes rows.""" require(persist or not rebuild, "DOMAIN_INDEX_CORRUPT", "a rebuild must persist") snapshot = catalog.get(snapshot_id, "graph-snapshot") snapshot_hash = catalog.hash(snapshot_id) rows = authoritative_rows(catalog, snapshot) + if metrics is not None: + metrics["mode"] = "PROJECTED" if not self.tables_exist(): if not persist: return rows @@ -132,6 +134,8 @@ def read(self, catalog: Catalog, snapshot_id: str, *, rebuild: bool = False, return rows else: require(existing == expected_meta, "DOMAIN_INDEX_CORRUPT", "index metadata differs from authoritative snapshot") + if metrics is not None: + metrics["mode"] = "REBUILT" if rebuild else ("MATERIALIZED" if existing is None else "VERIFIED") try: actual = {source_id: loads(body) for source_id, body in self.db.execute( "SELECT source_id,body FROM trace_domain_index_sources WHERE snapshot_hash=? ORDER BY source_id", (snapshot_hash,))} diff --git a/trace_gc/retrieval/domains.py b/trace_gc/retrieval/domains.py index ba4bd8a..a37c0a1 100644 --- a/trace_gc/retrieval/domains.py +++ b/trace_gc/retrieval/domains.py @@ -16,6 +16,7 @@ from ..domains import verify_taxonomy from ..errors import require from ..schema import validate +from .telemetry import active, domain_hop DOMAIN_SELECTION_VERSION = "authorized-research-domain-selection-v1" LITERAL_CONFLICTS = "literal-v1" @@ -352,6 +353,22 @@ def _unprovable_edges(self) -> set[str]: state[stack[-1][0]] = True return {ref for ref, bad in state.items() if bad} + def measure_transition(self, left: str | None, right: str, *, channel: str) -> None: + if left is None or left == right or not active() or left not in self.edges or right not in self.edges: + return + def memberships(ref: str) -> set[tuple[str, str]]: + rows = self._source_rows + if not self.enabled: + catalog = self.view.catalog + sources = {catalog.get(evidence, "evidence")["source_snapshot_id"] + for evidence in self.edges[ref]["evidence_ids"]} + rows = {source: self.view.source_classification(source, self.access) for source in sources} + else: + sources = self._edge_sources[ref] + return {(row["taxonomy_hash"], domain) for source in sources + if (row := rows.get(source)) for domain in row["domain_ids"]} + domain_hop(memberships(left), memberships(right), channel=channel) + def closure(self, seeds: set[str]) -> set[str]: return self._closure(frozenset(seeds), probe=False)[0] @@ -362,9 +379,9 @@ def _closure(self, key: frozenset[str], *, probe: bool) -> tuple[set[str], bool] blocked = False included: set[str] = set() expanded: dict[str, bool] = {} - pending = deque((ref, True) for ref in sorted(seeds)) + pending = deque((ref, True, None) for ref in sorted(seeds)) while pending: - edge_id, expand_distinctions = pending.popleft() + edge_id, expand_distinctions, predecessor = pending.popleft() # Revisit at most once when an equivalence-only proof later becomes # a genuine selected/conflicting fact. False never downgrades True. if edge_id in expanded and (expanded[edge_id] or not expand_distinctions): @@ -375,6 +392,7 @@ def _closure(self, key: frozenset[str], *, probe: bool) -> tuple[set[str], bool] require(probe, "ACCESS_DENIED", "closure requires an unauthorized or unavailable prerequisite") blocked = True continue + self.measure_transition(predecessor, edge_id, channel="required_closure") included.add(edge_id) expanded[edge_id] = expand_distinctions a = self.edges[edge_id]["assertion"] @@ -382,9 +400,9 @@ def _closure(self, key: frozenset[str], *, probe: bool) -> tuple[set[str], bool] conflicts = self._conflict_neighbors.get(edge_id, set()) self.work(len(parents) + len(conflicts)) for parent in sorted(parents): - pending.append((parent, True)) + pending.append((parent, True, edge_id)) for other in sorted(conflicts): - pending.append((other, expand_distinctions)) + pending.append((other, expand_distinctions, edge_id)) # Same-as proofs may be transitive. Different-from is a direct # distinction: bring the other endpoint's equivalence proof, but # never expand A != B != C, including through aliases of B. @@ -393,13 +411,13 @@ def _closure(self, key: frozenset[str], *, probe: bool) -> tuple[set[str], bool] equivalents = self._equivalence_incident.get(node, set()) self.work(len(equivalents)) for other in sorted(equivalents): - pending.append((other, extend)) + pending.append((other, extend, edge_id)) if extend: identities = self._identity_incident.get(node, set()) self.work(len(identities)) for other in sorted(identities): if self._identity_predicates[other] == "different_from": - pending.append((other, False)) + pending.append((other, False, edge_id)) self._closure_cache[(key, probe)] = (frozenset(included), blocked) return included, blocked diff --git a/trace_gc/retrieval/security.py b/trace_gc/retrieval/security.py index 4cd933a..23266fc 100644 --- a/trace_gc/retrieval/security.py +++ b/trace_gc/retrieval/security.py @@ -5,6 +5,7 @@ from ..canonical import digest from ..catalog import Catalog from ..errors import require +from .telemetry import measured_acl def access_policy(*, tenant: str, workspace: str, user: str, roles: list[str] | None = None, @@ -26,6 +27,7 @@ def grant(tenant: str, workspace: str, *, users: list[str] | None = None, class AccessFilter: + @measured_acl("__init__") def __init__(self, policy: dict[str, Any], catalog: Catalog, statuses: dict[str, Any], *, historical: bool = False): from ..schema import validate validate("graph-access", policy) @@ -35,6 +37,7 @@ def __init__(self, policy: dict[str, Any], catalog: Catalog, statuses: dict[str, def fingerprint(self) -> str: return digest({"acl": self.policy, "statuses": self.statuses}) + @measured_acl("allows") def allows(self, kind: str, ref: str) -> bool: p = self.policy g = p["grants"].get(f"{kind}:{ref}") @@ -44,6 +47,7 @@ def allows(self, kind: str, ref: str) -> bool: (not g["users"] or p["user"] in g["users"]) and (not g["roles"] or bool(set(g["roles"]) & set(p["roles"])))) + @measured_acl("source") def source(self, source_id: str, *, current_status: dict[str, Any] | None = None, catalog: Catalog | None = None) -> bool: authority = self.catalog if catalog is None else catalog @@ -55,6 +59,7 @@ def source(self, source_id: str, *, current_status: dict[str, Any] | None = None return (source["security_scope"] == self.policy["tenant"] and bool(status) and status["permission"] == "READ" and not status["tombstone"] and status["active"]) + @measured_acl("evidence") def evidence(self, ref: str) -> bool: if ref not in self.catalog: return False @@ -64,11 +69,13 @@ def evidence(self, ref: str) -> bool: self.catalog.verify_evidence(ref) # Existing Evidence Firewall. return True + @measured_acl("edge") def edge(self, ref: str, fact: dict[str, Any]) -> bool: a = fact["assertion"] return (self.allows("edge", ref) and self.allows("node", a["subject"]) and self.allows("node", a["object"]) and all(self.evidence(e) for e in fact["evidence_ids"])) + @measured_acl("decision") def decision(self, ref: str) -> bool: if not self.allows("decision", ref) or ref not in self.catalog: return False @@ -87,5 +94,6 @@ def decision(self, ref: str) -> bool: ids = list(set(ids) | set(c["evidence_ids"])) return all(self.evidence(e) for e in ids) + @measured_acl("require_scope") def require_scope(self, scope: str) -> None: require(scope == self.policy["tenant"], "SECURITY_SCOPE", "authenticated tenant differs from query") diff --git a/trace_gc/retrieval/service.py b/trace_gc/retrieval/service.py index f03ed99..3ad242f 100644 --- a/trace_gc/retrieval/service.py +++ b/trace_gc/retrieval/service.py @@ -16,6 +16,7 @@ from .strategies import BuiltinStrategy, GraphRetriever, SearchSpace from .domains import ResearchDomainSelection, identity_aware_scope, require_live_scope, validate_scope from ..domain_publication import classification_identity +from .telemetry import cache_event from .vector import EmbeddingModel, HashingEmbedding, terms @@ -33,8 +34,10 @@ def get(self, key: str) -> list[dict[str, Any]] | None: with self._lock: if key not in self._entries: self.misses += 1 + cache_event("misses") return None self.hits += 1 + cache_event("hits") self._entries.move_to_end(key) return deepcopy(self._entries[key]) @@ -47,9 +50,11 @@ def put(self, key: str, value: list[dict[str, Any]]) -> None: while len(self._entries) > self.capacity: self._entries.popitem(last=False) self.evictions += 1 + cache_event("evictions") def invalidate(self) -> None: with self._lock: + cache_event("invalidations", len(self._entries)) self.invalidations += len(self._entries) self._entries.clear() diff --git a/trace_gc/retrieval/store.py b/trace_gc/retrieval/store.py index 79ee940..c5c01a1 100644 --- a/trace_gc/retrieval/store.py +++ b/trace_gc/retrieval/store.py @@ -4,14 +4,15 @@ from copy import deepcopy from dataclasses import dataclass, field from threading import get_ident -from time import monotonic +from time import monotonic, perf_counter_ns from typing import Any, Callable, Protocol, runtime_checkable -from ..canonical import digest, loads +from ..canonical import canonical_bytes, digest, loads from ..catalog import Catalog from ..compiler import timestamp from ..errors import require from ..domain_publication import classification_identity, snapshot_body, verify_projection from .security import AccessFilter +from .telemetry import active, record_read_metrics from .domain_index import authoritative_rows, SQLiteClassificationIndex @dataclass @@ -233,8 +234,12 @@ def _view(self, query: dict[str, Any], *, rebuild: bool, persist: bool, classified = classification_identity(body)["migrated"] require(not classified or self.audit_trust is not None, "CLASSIFICATION_TRUST_REQUIRED", "classified reads require application-enrolled audit trust") + measuring = active() + audit_started = perf_counter_ns() if measuring else 0 audit = backend.audit(trust=self.audit_trust, required_sources=tuple(body["source_epochs"]) if classified else ()) + if measuring: + record_read_metrics(authority_audit_seconds=(perf_counter_ns() - audit_started) / 1e9) require(audit["classification_replay"] == "PASS", "REPLAY_CONTENT_UNAVAILABLE", "classification replay proof is unavailable") require(not classified or audit["classification_authority_verified"], "CLASSIFICATION_TRUST_REQUIRED", @@ -247,7 +252,15 @@ def _view(self, query: dict[str, Any], *, rebuild: bool, persist: bool, snapshot_id = catalog.put("graph-snapshot", body) # Compute/validate index ONLY from persisted authority, never proposals # carried in the caller's mutable working catalog. - rows = self.index.read(catalog, snapshot_id, rebuild=rebuild, persist=persist) + index_started = perf_counter_ns() if measuring else 0 + index_metrics = {} if measuring else None + rows = self.index.read(catalog, snapshot_id, rebuild=rebuild, persist=persist, metrics=index_metrics) + if measuring: + record_read_metrics( + validation_seconds=(perf_counter_ns() - index_started) / 1e9, + source_rows=len(rows), membership_rows=len(self.index.membership(rows)), + logical_source_row_bytes=len(canonical_bytes(rows)), **index_metrics, + ) if self.working_catalog is not None and version is None: for record in self.working_catalog.all(): catalog.add(record) diff --git a/trace_gc/retrieval/strategies.py b/trace_gc/retrieval/strategies.py index 1d462b3..94edd9e 100644 --- a/trace_gc/retrieval/strategies.py +++ b/trace_gc/retrieval/strategies.py @@ -96,6 +96,8 @@ def retrieve(self, space: SearchSpace) -> Iterable[dict[str, Any]]: m.work() if target in nodes: continue + if name == "PATH" and path: + space.domain_selection.measure_transition(path[-1], ref, channel="path") next_path = path + [ref] if name == "NEIGHBORHOOD" and ref not in visited_edges: visited_edges.add(ref) @@ -243,10 +245,10 @@ def retrieve(self, space: SearchSpace) -> Iterable[dict[str, Any]]: for root in sorted(focus or set(adj)): if root in seen: continue - nodes, members, queue = set(), set(), deque([root]) + nodes, members, queue = set(), set(), deque([(root, None)]) while queue: m.work() - node = queue.popleft() + node, predecessor = queue.popleft() if node in nodes: continue nodes.add(node) @@ -256,9 +258,11 @@ def retrieve(self, space: SearchSpace) -> Iterable[dict[str, Any]]: m.work() if len(members) >= m.limits.maximum_edges: break + if edge not in members: + space.domain_selection.measure_transition(predecessor, edge, channel="community") members.add(edge) if target not in nodes: - queue.append(target) + queue.append((target, edge)) seen.update(nodes) if members: ref = "community-" + digest(sorted(members))[:20] diff --git a/trace_gc/retrieval/telemetry.py b/trace_gc/retrieval/telemetry.py new file mode 100644 index 0000000..9bafb0a --- /dev/null +++ b/trace_gc/retrieval/telemetry.py @@ -0,0 +1,101 @@ +"""Opt-in, thread-local measurements; never scientific evidence or access policy. + +Counters stay outside canonical records and do not affect cache identities. +No query text, source text, credentials, or signing material is recorded here. +""" +from __future__ import annotations + +from collections import Counter +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass, field +from functools import wraps +from time import perf_counter_ns +from typing import Any, Iterator + + +@dataclass +class RetrievalMeasurements: + acl_calls: Counter = field(default_factory=Counter) + acl_elapsed_ns: int = 0 + domain_hops: Counter = field(default_factory=Counter) + cache: Counter = field(default_factory=Counter) + read_metrics: dict[str, Any] = field(default_factory=dict) + _acl_depth: int = 0 + + def as_dict(self) -> dict[str, Any]: + return {"acl_calls": dict(sorted(self.acl_calls.items())), + "acl_elapsed_ms": self.acl_elapsed_ns / 1_000_000, + "domain_hops": dict(sorted(self.domain_hops.items())), + "acl_timing": "outermost ACL call wall time; nested calls counted but not double-timed"} + + +_ACTIVE: ContextVar[RetrievalMeasurements | None] = ContextVar("trace_retrieval_measurements", default=None) + + +def active() -> bool: + return _ACTIVE.get() is not None + + +@contextmanager +def measure_retrieval() -> Iterator[RetrievalMeasurements]: + measurement = RetrievalMeasurements() + token = _ACTIVE.set(measurement) + try: + yield measurement + finally: + _ACTIVE.reset(token) + + +def measured_acl(name: str): + """Measure a guard without changing its return, exception, or deny behavior.""" + def decorate(function): + @wraps(function) + def measured(*args, **kwargs): + measurement = _ACTIVE.get() + if measurement is None: + return function(*args, **kwargs) + outer = measurement._acl_depth == 0 + start = perf_counter_ns() if outer else 0 + measurement.acl_calls[name] += 1 + measurement._acl_depth += 1 + try: + return function(*args, **kwargs) + finally: + measurement._acl_depth -= 1 + if outer: + measurement.acl_elapsed_ns += perf_counter_ns() - start + return measured + return decorate + + +def domain_hop(left: set[tuple[str, str]], right: set[tuple[str, str]], *, channel: str) -> None: + """Call only after both edges and their sources have passed current ACLs. + + Each pair is (immutable taxonomy hash, stable domain ID). Unknown membership + is counted separately, never called a cross-domain or same-domain success. + Counts are executed transitions, not unique edges or distributed RPCs. + """ + measurement = _ACTIVE.get() + if measurement is None: + return + measurement.domain_hops[channel + ":transitions"] += 1 + if not left or not right: + measurement.domain_hops[channel + ":unclassified_transitions"] += 1 + else: + if left != right: + measurement.domain_hops[channel + ":membership_changing_transitions"] += 1 + if not left.intersection(right): + measurement.domain_hops[channel + ":disjoint_domain_transitions"] += 1 + + +def cache_event(name: str, count: int = 1) -> None: + measurement = _ACTIVE.get() + if measurement is not None: + measurement.cache[name] += count + + +def record_read_metrics(**values: Any) -> None: + measurement = _ACTIVE.get() + if measurement is not None: + measurement.read_metrics.update(values) diff --git a/trace_gc/retrieval/workloads.py b/trace_gc/retrieval/workloads.py new file mode 100644 index 0000000..d700176 --- /dev/null +++ b/trace_gc/retrieval/workloads.py @@ -0,0 +1,551 @@ +"""Measured query/write workloads with explicit synthetic/representative boundaries. + +The default command runs only fabricated data and disposable reference databases. +Applications may reuse the recorder with representative cases and their existing +trusted services. The recorder never creates permissions, approvals, or signers. +""" +from __future__ import annotations + +from collections import Counter +from contextlib import contextmanager +import re +from concurrent.futures import ThreadPoolExecutor +from copy import deepcopy +from dataclasses import dataclass, field +import math +from pathlib import Path +import platform +import tempfile +import threading +from time import perf_counter_ns +from typing import Any, Callable + +from ..canonical import digest, write +from ..domain_publication import classification_identity, empty_projection +from ..errors import ContractError, require +from .telemetry import measure_retrieval + +VERSION = "research-domain-workloads-v1.2" +REFERENCE_QUERY_TIME = "2026-09-27T00:00:00Z" + + +def percentiles(values: list[float]) -> dict[str, float | int | None]: + """Nearest-rank quantiles, including small-sample count (not confidence bounds).""" + require(all(type(x) in (int, float) and math.isfinite(x) and x >= 0 for x in values), + "WORKLOAD_METRIC", "finite nonnegative observations required") + ordered = sorted(values) + result: dict[str, Any] = {"count": len(ordered)} + for label, p in (("p50", .5), ("p95", .95), ("p99", .99)): + result[label] = ordered[max(0, math.ceil(p * len(ordered)) - 1)] if ordered else None + result["maximum"] = max(ordered) if ordered else None + return result + + +def topology(snapshot: dict[str, Any]) -> dict[str, Any]: + """Actual active original-assertion degree, not canonicalized edge cardinality. + + Administrative telemetry can reveal graph size and belongs behind a separate + operational access boundary. It is not emitted into end-user query contexts. + """ + degree = Counter({ref: 0 for ref in snapshot["nodes"]}) + active = 0 + for fact in snapshot["assertions"].values(): + if fact["active"]: + active += 1 + degree.update({fact["assertion"]["subject"], fact["assertion"]["object"]}) + values = sorted(degree.values()) + n, total = len(values), sum(values) + gini = (2 * sum((i + 1) * value for i, value in enumerate(values)) / (n * total) - (n + 1) / n) if n and total else 0.0 + top = max(1, math.ceil(n * .01)) + return {"nodes": n, "active_original_assertions": active, "degree": percentiles(values), + "degree_gini": gini, "top_one_percent_node_degree_share": sum(values[-top:]) / total if total else 0.0, + "degree_definition": "incident active original assertions; a self-loop is counted once"} + + +@dataclass(frozen=True) +class QueryCase: + case_id: str + request: dict[str, Any] + relevant_evidence_ids: frozenset[str] = field(default_factory=frozenset) + required_contradictions: tuple[frozenset[str], ...] = () + forbidden_source_ids: frozenset[str] = field(default_factory=frozenset) + pair_id: str | None = None + required_conflict_edges: tuple[frozenset[str], ...] = () + + def __post_init__(self): + require(bool(self.case_id), "WORKLOAD_CASE", "stable case ID required") + require(all(len(pair) >= 2 for pair in (*self.required_contradictions, *self.required_conflict_edges)), + "WORKLOAD_CASE", "a contradiction expectation needs both evidence sides") + + +class WorkloadRecorder: + """Bounded thread-safe telemetry sink. No embedded query/source text or secrets.""" + def __init__(self, *, input_manifest: dict[str, Any], maximum_samples: int = 100000): + require(type(maximum_samples) is int and maximum_samples > 0, "WORKLOAD_METRIC", "positive sample bound required") + require(input_manifest.get("data_kind") in {"SYNTHETIC", "REPRESENTATIVE_CANDIDATE"} and + all(isinstance(input_manifest.get(k), str) and input_manifest[k] for k in + ("corpus_hash", "labels_hash", "protocol_id")), + "WORKLOAD_INPUT", "explicit corpus, label and protocol provenance required") + self.input_manifest = deepcopy(input_manifest) + require(all(re.fullmatch(r"[0-9a-f]{64}", input_manifest[k]) for k in ("corpus_hash", "labels_hash")), + "WORKLOAD_INPUT", "corpus and labels must be bound to SHA-256 digests") + self.maximum_samples = maximum_samples + self._reserved = 0 + self.samples: list[dict[str, Any]] = [] + self._lock = threading.RLock() + + def append(self, sample: dict[str, Any]) -> None: + with self._lock: + require(len(self.samples) + self._reserved < self.maximum_samples, "WORKLOAD_LIMIT", "telemetry sample bound reached") + self.samples.append(deepcopy(sample)) + + @contextmanager + def slot(self): + # Reserve BEFORE work: exhausted telemetry capacity must not turn a + # successfully committed publication into a reporting exception afterward. + with self._lock: + require(len(self.samples) + self._reserved < self.maximum_samples, + "WORKLOAD_LIMIT", "telemetry sample bound reached before execution") + self._reserved += 1 + recorder = self + class Slot: + submitted = False + def append(self, sample): + with recorder._lock: + require(not self.submitted, "WORKLOAD_METRIC", "one measurement per reserved operation") + recorder.samples.append(deepcopy(sample)) + recorder._reserved -= 1 + self.submitted = True + slot = Slot() + try: + yield slot + finally: + with self._lock: + if not slot.submitted: + self._reserved -= 1 + + def report(self) -> dict[str, Any]: + with self._lock: + require(self._reserved == 0, "WORKLOAD_INCOMPLETE", "operations are still being measured") + samples = deepcopy(self.samples) + queries = [s for s in samples if s["kind"] == "QUERY"] + writes = [s for s in samples if s["kind"] == "PUBLICATION"] + groups = {} + for operation in {s["operation"] for s in samples}: + rows = [s for s in samples if s["operation"] == operation] + groups[operation] = {"latency_ms": percentiles([s["elapsed_ms"] for s in rows]), + "outcomes": dict(Counter(s["outcome"] for s in rows))} + # Costs include failed work. Quality is meaningful only for returned + # contexts; a denial is not a zero-error/zero-recall retrieval success. + successful = [q for q in queries if q.get("completed", q["outcome"] in {"COMPLETE", "PARTIAL", "EMPTY"}) + and isinstance(q.get("quality"), dict)] + measured = [q for q in queries if "measurements" in q and "cache_delta" in q] + quality = {} + for scoped in (False, True): + rows = [q for q in successful if q["domain_scoped"] == scoped] + recalls = [q["quality"]["evidence_recall"] for q in rows if q["quality"]["evidence_recall"] is not None] + quality["scoped" if scoped else "unscoped"] = { + "queries": len(rows), "labeled_queries": len(recalls), + "mean_evidence_recall": sum(recalls) / len(recalls) if recalls else None, + "missed_contradiction_pairs": sum(q["quality"]["missed_contradiction_pairs"] for q in rows), + "forbidden_sources_returned": sum(q["quality"]["forbidden_sources_returned"] for q in rows)} + def missing_conflict_edges(rows): + counts = [q["quality"].get("missing_structured_conflicts") for q in rows] + observed = [count for count in counts if count is not None] + return sum(observed) if observed else None + + paired = {} + for pair_id in sorted({q["pair_id"] for q in successful if q["pair_id"] is not None}): + paired[pair_id] = {} + for scoped in (False, True): + rows = [q for q in successful if q["pair_id"] == pair_id and q["domain_scoped"] == scoped] + recalls = [q["quality"]["evidence_recall"] for q in rows if q["quality"]["evidence_recall"] is not None] + paired[pair_id]["scoped" if scoped else "unscoped"] = { + "queries": len(rows), "latency_ms": percentiles([q["elapsed_ms"] for q in rows]), + "mean_evidence_recall": sum(recalls) / len(recalls) if recalls else None, + "missed_contradiction_pairs": sum(q["quality"]["missed_contradiction_pairs"] for q in rows), + "missing_structured_conflicts": missing_conflict_edges(rows)} + index_modes = {q["adapter_metrics"]["mode"] for q in measured if "mode" in q.get("adapter_metrics", {})} + index_latency = {mode: percentiles([q["adapter_metrics"]["validation_seconds"] * 1000 for q in measured + if q.get("adapter_metrics", {}).get("mode") == mode]) for mode in sorted(index_modes)} + hops = Counter() + for row in measured: + hops.update(row["measurements"]["domain_hops"]) + committed = [w for w in writes if w["outcome"] == "COMMITTED"] + classified_writes = [w for w in committed if w["write_domains"] is not None] + cross = sum(w["write_domains"]["cross_domain_batch"] for w in classified_writes) + return {"version": VERSION, "status": "MEASURED_NOT_QUALIFIED", "input_manifest": self.input_manifest, + "environment": {"python": platform.python_version(), "platform": platform.platform()}, + "sample_count": len(samples), "operations": dict(sorted(groups.items())), + "query_latency_ms": percentiles([q["elapsed_ms"] for q in queries]), + "query_outcomes": {"completed": len(successful), "rejected_or_error": len(queries) - len(successful)}, + "telemetry_coverage": {"queries": len(queries), "measured_queries": len(measured), + "unmeasured_queries": len(queries) - len(measured)}, + "publication_latency_ms": percentiles([w["elapsed_ms"] for w in writes]), + "committed_publication_latency_ms": percentiles([w["elapsed_ms"] for w in committed]), + "acl_elapsed_ms": percentiles([q["measurements"]["acl_elapsed_ms"] for q in measured]), + "index_validation_ms": percentiles([q["adapter_metrics"]["validation_seconds"] * 1000 + for q in measured if "validation_seconds" in q.get("adapter_metrics", {})]), + "index_latency_ms_by_mode": index_latency, + "publication_domain_coverage": {"committed": len(committed), "classified": len(classified_writes)}, + "authority_audit_ms": percentiles([q["adapter_metrics"]["authority_audit_seconds"] * 1000 + for q in measured if "authority_audit_seconds" in q.get("adapter_metrics", {})]), + "cache": {name: sum(q["cache_delta"][name] for q in measured) + for name in ("hits", "misses", "invalidations", "evictions")}, + "domain_hops": dict(sorted(hops.items())), "quality": quality, "paired_comparison": paired, + "writes": {"committed": len(committed), "cross_domain_batches": cross, + "cross_domain_batch_rate": cross / len(classified_writes) if classified_writes else None, + "replayed": sum(w["outcome"] == "REPLAYED" for w in writes), + "rejected": sum(w["outcome"] not in {"COMMITTED", "REPLAYED"} for w in writes)}, + "qualification": {"representativeness": "NOT_ESTABLISHED", "independent_labels": "NOT_ESTABLISHED", + "deployment_slos": "NOT_EVALUATED", "storage_decision_owner": "NOT_SELECTED", + "production_backend": "NOT_QUALIFIED"}, + "limitations": ["No synthetic node count or latency threshold authorizes physical sharding.", + "Nearest-rank quantiles have no statistical confidence claim; inspect sample counts.", + "ACL/cache/traversal costs include recorded rejections and operational errors; quality excludes them.", + "Missing telemetry on imported legacy rows is reported as unmeasured, not imputed as zero cost.", + "Cross-domain hops count executed path/community/required-closure transitions, including revalidation; not network RPCs.", + "Write latency excludes caller plan preparation/signing and includes trusted publish validation/commit.", + "Hash-bound representative-candidate metadata is not an approval or independent qualification."], + "samples": samples} + + +def measure_query(retriever: Any, case: QueryCase, recorder: WorkloadRecorder) -> str: + with recorder.slot() as slot: + return _measure_query(retriever, case, slot) + + +def _measure_query(retriever: Any, case: QueryCase, recorder: Any) -> str: + # Keep the result and its catalog view consistent through observation. + with retriever._lock: + result_id = None + # Malformed requests still need failure telemetry. Hashing a NaN or + # invalid Unicode must not replace the retriever's original exception. + try: + request_hash = digest(case.request) + request_hash_status = "HASHED" + except ContractError: + request_hash = None + request_hash_status = "UNAVAILABLE_NONCANONICAL_REQUEST" + started = perf_counter_ns() + with measure_retrieval() as measurements: + try: + result_id = retriever.retrieve(case.request) + result = retriever.catalog.get(result_id, "retrieval-result") + context = retriever.catalog.get(result["graph_context_id"], "graph-context") + outcome = result["status"] + except Exception as exc: + # Preserve the exact exception for the caller. Do not log its + # message, stack, provider response, or any query/source text. + recorder.append({"kind": "QUERY", "case_id": case.case_id, "pair_id": case.pair_id, + "operation": "query:rejected", "request_hash": request_hash, "request_hash_status": request_hash_status, + "outcome": exc.code if isinstance(exc, ContractError) else "ERROR", + "completed": False, "error_type": type(exc).__name__, + "domain_scoped": case.request.get("research_domain_scope") is not None, + "elapsed_ms": (perf_counter_ns() - started) / 1_000_000, + "graph_version": None, "classification_identity": None, "quality": None, + "adapter_metrics": dict(measurements.read_metrics), + "measurements": measurements.as_dict(), + "cache_delta": {name: measurements.cache[name] for name in ("hits", "misses", "invalidations", "evictions")}}) + raise + elapsed = (perf_counter_ns() - started) / 1_000_000 + evidence = set(context["selected_evidence_ids"]) + conflict_items = [set(item["assertion_ids"]) for item in context["items"] if item["kind"] == "CONFLICT"] + sources = {s for item in context["items"] for s in item["source_ids"]} + sources.update(retriever.catalog.get(ref, "evidence")["source_snapshot_id"] for ref in evidence) + scope = case.request.get("research_domain_scope") + sample = {"kind": "QUERY", "case_id": case.case_id, "pair_id": case.pair_id, + "operation": "query:" + ("scoped:" if scope else "unscoped:") + "+".join(case.request["retrieval_strategy"]), + "request_hash": request_hash, "request_hash_status": request_hash_status, "outcome": outcome, "elapsed_ms": elapsed, "domain_scoped": scope is not None, + "completed": True, "error_type": None, + "graph_version": context["graph_version"], "classification_identity": context.get("classification_identity"), + "adapter_metrics": dict(measurements.read_metrics), "measurements": measurements.as_dict(), + "cache_delta": {name: measurements.cache[name] for name in ("hits", "misses", "invalidations", "evictions")}, + "quality": {"evidence_recall": len(evidence & case.relevant_evidence_ids) / len(case.relevant_evidence_ids) + if case.relevant_evidence_ids else None, + "missed_contradiction_pairs": sum(not pair <= evidence for pair in case.required_contradictions), + "forbidden_sources_returned": len(sources & case.forbidden_source_ids), + "missing_structured_conflicts": sum(not any(pair <= item for item in conflict_items) + for pair in case.required_conflict_edges) if case.required_conflict_edges else None}, + "usage": deepcopy(result["usage"]), "selected_assertion_count": len(context["retrieved_edges"]), + "selected_source_count": len(sources), "context_hash": retriever.catalog.hash(result["graph_context_id"])} + recorder.append(sample) + return result_id + + +def _source_labels(catalog, state, source_id) -> set[tuple[str, str]] | None: + assignment_id = state.get("classifications", empty_projection())["assignments"].get(source_id) + if assignment_id is None: + return set() + if assignment_id not in catalog: + return None + assignment = catalog.get(assignment_id, "classification-assignment") + return {(assignment["taxonomy_hash"], label) for label in assignment["domain_ids"]} + + +def measure_publication(service: Any, catalog: Any, plan_id: str, recorder: WorkloadRecorder, *, + authorization: dict[str, Any], preflight: dict[str, Any]) -> dict[str, Any]: + with recorder.slot() as slot: + return _measure_publication(service, catalog, plan_id, slot, authorization=authorization, preflight=preflight) + + +def _measure_publication(service: Any, catalog: Any, plan_id: str, recorder: Any, *, + authorization: dict[str, Any], preflight: dict[str, Any]) -> dict[str, Any]: + """No approving authority here: callers must supply the normal signed receipts.""" + started = perf_counter_ns() + try: + result = service.publish(catalog, plan_id, authorization=authorization, preflight=preflight) + except Exception as exc: + recorder.append({"kind": "PUBLICATION", "operation": "publication", + "outcome": exc.code if isinstance(exc, ContractError) else "ERROR", + "elapsed_ms": (perf_counter_ns() - started) / 1_000_000}) + raise + elapsed = (perf_counter_ns() - started) / 1_000_000 + event = result["event"] + plan = catalog.get(plan_id, "plan") + after = event["state_after"] + before_id = plan["snapshot_id"] + refs = set(plan["source_epochs"]) + write_domains = None + # The accepted event binds this exact signed predecessor. Retention can + # remove predecessor content before an otherwise valid receipt replay. + if before_id in catalog: + before = catalog.get(before_id, "graph-snapshot") + before_labels = [_source_labels(catalog, before, ref) for ref in refs] + after_labels = [_source_labels(catalog, after, ref) for ref in refs] + if None not in before_labels and None not in after_labels: + labels = set().union(*before_labels, *after_labels) + multi = sum(len(labels_for_source) > 1 for labels_for_source in after_labels) + write_domains = {"touched_sources": len(refs), "distinct_taxonomy_domain_pairs": len(labels), + "multi_domain_sources_after": multi, "cross_domain_batch": len(labels) > 1} + recorder.append({"kind": "PUBLICATION", "operation": "publication", "plan_hash": catalog.hash(plan_id), + "outcome": "REPLAYED" if result["replayed"] else "COMMITTED", "elapsed_ms": elapsed, + "event_hash": event["hash"], "graph_version": event["version"], "classification_identity": classification_identity(after), + "write_domains": write_domains, + "write_definition": "domain union of exact signed-plan predecessor and event poststate source assignments; retries are not writes"}) + return result + + +def run_query_workload(factory: Callable[[], Any], cases: list[QueryCase], recorder: WorkloadRecorder, *, + repetitions: int = 3, workers: int = 1) -> None: + require(type(repetitions) is int and repetitions > 0 and type(workers) is int and 1 <= workers <= 32 and bool(cases), + "WORKLOAD_INPUT", "nonempty cases, positive repetitions and 1..32 workers required") + def execute(worker): + retriever = factory() + for _ in range(repetitions): + for case in cases: + measure_query(retriever, case, recorder) + with ThreadPoolExecutor(max_workers=workers) as pool: + list(pool.map(execute, range(workers))) + + +def run_reference_domain_workload(output: str | Path | None = None, *, repetitions: int = 3, workers: int = 2) -> dict[str, Any]: + """Offline synthetic smoke, not representative or deployment-like qualification.""" + from .contracts import query, RetrievalBudget + + from .domains import research_domain_scope + from .fixtures import domain_corpus, demo_access, SCOPE as READ_SCOPE + from .service import HybridRetriever, RetrievalCache + from .store import InMemoryGraphAdapter, SQLiteGraphAdapter + from ..backend import CompilerService + from ..catalog import Catalog + from ..compiler import now + from ..demo import build_fixture, POLICY, POPULATION, SCOPE, RUN + from ..domain_publication import classification_operation, migration_operation + from ..domains import reference_taxonomy, create_assignment + from ..plans import create_plan + from ..trust import Signer, IssuerPolicy, authorize_plan + + fixture = domain_corpus() + c = fixture["catalog"] + snapshot = c.get(fixture["snapshot_id"]) + scope = research_domain_scope(c, fixture["taxonomy_id"], ["research:biology"]) + budget = RetrievalBudget(maximum_nodes=100, maximum_edges=100, maximum_source_spans=100, + maximum_tokens=150000, maximum_latency_ms=30000) + cases = [] + for name, strategies, text, focus in (("lexical-conflict", ["LEXICAL"], "improves", []), + ("vector-conflict", ["VECTOR"], "improves", []), + ("path", ["PATH"], "Acme", ["Acme"]), ("community", ["COMMUNITY"], "Acme", ["Acme"])): + relevant = frozenset({fixture["evidence"]["e-support"], fixture["evidence"]["e-refute"]}) if "conflict" in name else frozenset() + contradictions = (relevant,) if relevant else () + for selection in (None, scope): + case_id = name + (":scoped" if selection else ":unscoped") + request = query(requesting_component="downstream-search", security_scope=READ_SCOPE, strategies=strategies, + text=text, focus_entities=focus, hop_limit=2, research_domain_scope=selection, created_at=REFERENCE_QUERY_TIME, + include_conflicts=True, budget=budget) + structured = (frozenset({"e-support", "e-refute"}),) if relevant else () + cases.append(QueryCase(case_id, request, relevant, contradictions, pair_id=name, required_conflict_edges=structured)) + denied_case = QueryCase("acl-scope-rejected", query(requesting_component="downstream-search", + security_scope="not-authorized:" + READ_SCOPE, strategies=["LEXICAL"], text="improves", + research_domain_scope=scope, budget=budget, created_at=REFERENCE_QUERY_TIME)) + protocol_cases = [*cases, denied_case] + recorder = WorkloadRecorder(input_manifest={"data_kind": "SYNTHETIC", "protocol_id": VERSION, + "corpus_hash": c.hash(fixture["snapshot_id"]), "labels_hash": digest({case.case_id: {"relevant_evidence": sorted(case.relevant_evidence_ids), + "required_contradictions": [sorted(pair) for pair in case.required_contradictions], + "required_conflict_edges": [sorted(pair) for pair in case.required_conflict_edges], + "forbidden_sources": sorted(case.forbidden_source_ids), "pair_id": case.pair_id} for case in protocol_cases}), + "query_protocol_hash": digest({case.case_id: case.request for case in protocol_cases}), + "expected_query_rejections": {denied_case.case_id: "SECURITY_SCOPE"}, + "label_origin": "FABRICATED_FIXTURE_NOT_INDEPENDENT", "owner": None, "slo": None, + "isolation_requirements": None, "concurrency": {"workers": workers, "repetitions_per_worker": repetitions, + "kind": "same-process threads over immutable in-memory reference snapshots; not deployment-like concurrency"}}) + def factory(): + copied = Catalog(c.all()) + adapter = InMemoryGraphAdapter(copied, fixture["adapter"].snapshot_ids, fixture["adapter"].source_status) + return HybridRetriever(adapter, catalog=copied, access_policy=fixture["retriever"].access_policy, + cache=RetrievalCache(capacity=4)) + run_query_workload(factory, cases, recorder, repetitions=repetitions, workers=workers) + # One separately declared negative case exercises failure cost accounting. + # It cannot be included as a successful quality observation or an access grant. + try: + measure_query(factory(), denied_case, recorder) + except ContractError as exc: + require(exc.code == "SECURITY_SCOPE", "WORKLOAD_EXPECTATION", "unexpected negative-case outcome") + else: + raise ContractError("WORKLOAD_EXPECTATION", "unauthorized scope was not rejected") + # Separate actual SQLite write/read/cache-churn phase. Its timing is not mixed + # into a claim that the in-memory graph represents a deployment database. + with tempfile.TemporaryDirectory(prefix="trace-domain-workload-") as directory: + f = build_fixture(Path(directory)) + try: + f.publish() + sqlite_inputs = {"snapshot_hash": f.catalog.hash(f.backend.snapshot(f.catalog)), + "source_hashes": sorted(f.catalog.hash(ref) for ref in f.source_ids), + "evidence_hashes": sorted(f.catalog.hash(ref) for ref in f.evidence_ids), + "label_origin": "FABRICATED_FIXTURE_NOT_INDEPENDENT"} + signer = Signer.ephemeral("workload-reviewer") + f.trust.enroll(signer.issuer, IssuerPolicy(signer.public_key(), "synthetic-workload-reviewer", + frozenset({"AUTHORIZATION"}), frozenset({"INITIALIZE_RESEARCH_DOMAINS", "SET_SOURCE_CLASSIFICATION"}), + frozenset({SCOPE}), frozenset({"SYNTHETIC"}), can_review=True)) + taxonomy = reference_taxonomy()["body"] + review = {"status": "APPROVED", "reviewer_id": "synthetic-workload-reviewer", "reviewed_at": now(), + "rationale": "Fabricated offline workload; not independently reviewed scientific labels"} + taxonomy["review"] = review + taxonomy_id = f.catalog.put("research-domain-taxonomy", taxonomy) + service = CompilerService(f.backend, f.trust, f.validator, policy_version=POLICY, population=POPULATION, + security_scope=SCOPE, publication_mode="REVIEWED", policy_hash=f.catalog.hash(f.policy_id), + classification_enabled=True, classification_taxonomy_hashes=frozenset({f.catalog.hash(taxonomy_id)})) + def publish(ops, key): + pid = create_plan(f.catalog, run_id=RUN, snapshot_id=f.backend.snapshot(f.catalog), operations=ops, + security_scope=SCOPE, execution_mode="SYNTHETIC", idempotency_key=key, + policy_version=POLICY, source_status=f.backend.statuses()) + auth = authorize_plan(signer, f.catalog.get(pid), f.catalog.hash(pid), reviewed_by="synthetic-workload-reviewer") + preflight = service.preflight(f.catalog, pid, reviewed=True) + result = measure_publication(service, f.catalog, pid, recorder, authorization=auth, preflight=preflight) + measure_publication(service, f.catalog, pid, recorder, authorization=auth, preflight=preflight) + return result + publish([migration_operation(operation_id="initialize", reason="Synthetic workload migration")], "workload-initialize") + reader = HybridRetriever(SQLiteGraphAdapter(f.backend, audit_trust=f.trust), catalog=f.catalog, + access_policy=demo_access(f.catalog, f.backend.snapshot(f.catalog), scope=SCOPE), cache=RetrievalCache(capacity=4)) + labels = research_domain_scope(f.catalog, taxonomy_id, ["research:biology"]) + request = query(requesting_component="downstream-search", security_scope=SCOPE, strategies=["LEXICAL"], + text="Aster", research_domain_scope=labels, include_conflicts=False, budget=budget, created_at=REFERENCE_QUERY_TIME) + previous = None + index_preparations = [] + cold_projection = None + + def prepare_index(request, *, rebuild=False): + operation = (reader.adapter.rebuild_classification_index if rebuild + else reader.adapter.materialize_classification_index) + with measure_retrieval() as metrics: + operation(request) + index_preparations.append(dict(metrics.read_metrics)) + for revision in range(1, max(3, repetitions) + 1): + assignment = create_assignment(f.catalog, source_snapshot_id=f.source_ids[0], taxonomy_id=taxonomy_id, + domain_ids=["research:biology", "research:chemistry"] if revision % 2 else ["research:physics"], + classifier_id="synthetic-workload-reviewer", classifier_version=VERSION, review=review, supersedes=previous) + publish([classification_operation(f.catalog, assignment, operation_id="assign")], "workload-assign-" + str(revision)) + previous = assignment + expected = frozenset({f.evidence_ids[0]}) if revision % 2 else frozenset() + case = QueryCase("sqlite-reclassification-" + str(revision), request, expected) + if revision == 1: + with measure_retrieval() as metrics: + reader.adapter.read(request) + cold_projection = dict(metrics.read_metrics) + prepare_index(request, rebuild=revision == 1) + measure_query(reader, case, recorder) + measure_query(reader, case, recorder) + historical_version = f.backend.state()["graph_version"] + f.status_change(f.source_ids[0]) + # A historically matching assignment must still exclude the now-revoked source. + revoked_case = QueryCase("sqlite-historical-current-revocation", {**request, "graph_version": historical_version, + "include_historical": True}, forbidden_source_ids=frozenset({f.source_ids[0]})) + measure_query(reader, revoked_case, recorder) + # Actual concurrent writers against TWO connections to ONE SQLite + # authority. The stale loser is recorded, never treated as a write. + from ..backend import SQLiteReferenceBackend + concurrent = SQLiteReferenceBackend(f.backend.path, catalog=f.catalog, schema_id=f.schema_id, + nodes=f.backend.state()["nodes"], sandbox=True) + try: + jobs = [] + for i, backend in enumerate((f.backend, concurrent)): + cc = Catalog(f.catalog.all()) + assignment = create_assignment(cc, source_snapshot_id=f.source_ids[1], taxonomy_id=taxonomy_id, + domain_ids=["research:chemistry"] if i else ["research:physics"], classifier_id="synthetic-workload-reviewer", + classifier_version=VERSION, review=review) + pid = create_plan(cc, run_id=RUN, snapshot_id=backend.snapshot(cc), + operations=[classification_operation(cc, assignment, operation_id="concurrent-assign")], + security_scope=SCOPE, execution_mode="SYNTHETIC", idempotency_key="concurrent-" + str(i), + policy_version=POLICY, source_status=backend.statuses()) + ss = CompilerService(backend, f.trust, f.validator, policy_version=POLICY, population=POPULATION, + security_scope=SCOPE, publication_mode="REVIEWED", policy_hash=cc.hash(f.policy_id), + classification_enabled=True, classification_taxonomy_hashes=frozenset({cc.hash(taxonomy_id)})) + auth = authorize_plan(signer, cc.get(pid), cc.hash(pid), reviewed_by="synthetic-workload-reviewer") + jobs.append((ss, cc, pid, auth, ss.preflight(cc, pid, reviewed=True))) + barrier = threading.Barrier(2) + def concurrent_publish(job): + ss, cc, pid, auth, preflight = job + barrier.wait(timeout=10) + try: + measure_publication(ss, cc, pid, recorder, authorization=auth, preflight=preflight) + return "COMMITTED" + except ContractError as exc: + return exc.code + with ThreadPoolExecutor(max_workers=2) as pool: + concurrent_outcomes = list(pool.map(concurrent_publish, jobs)) + require(sorted(concurrent_outcomes) == ["COMMITTED", "STALE_GRAPH_VERSION"], + "WORKLOAD_CONCURRENCY", "exactly one of two same-version writers must commit") + finally: + concurrent.close() + audit = f.backend.audit(trust=f.trust) + sqlite_topology = topology(f.backend.state()) + try: + index_pages = dict(f.backend.db.execute("SELECT name,sum(pgsize) FROM dbstat WHERE name LIKE 'trace_domain_index_%' OR name LIKE 'sqlite_autoindex_trace_domain_index_%' GROUP BY name")) + except Exception: + index_pages = None + sizes = {"index_btree_bytes_by_object": index_pages, "index_btree_measurement": "dbstat" if index_pages is not None else "UNAVAILABLE", + "page_bytes": f.backend.db.execute("PRAGMA page_size").fetchone()[0] * f.backend.db.execute("PRAGMA page_count").fetchone()[0], + "main_file_bytes": Path(f.backend.path).stat().st_size, + "wal_file_bytes": Path(f.backend.path + "-wal").stat().st_size if Path(f.backend.path + "-wal").exists() else 0, + "scope": "local reference database/WAL only; not resident set size or a distributed index"} + finally: + f.close() + report = recorder.report() + report.update(topology={"memory_read_fixture": topology(snapshot), "sqlite_write_fixture": sqlite_topology}, + sqlite_storage=sizes, index_preparations=index_preparations, cold_projection=cold_projection, sqlite_input_manifest=sqlite_inputs, sqlite_audit=audit, concurrent_write_outcomes=concurrent_outcomes, + provider_calls=0, production_graph_writes=0, + placement_decision="DEFERRED_PENDING_REPRESENTATIVE_DATA_OWNER_ISOLATION_AND_SLOS") + # Linux process-wide observations, not an isolated workload's memory demand. + memory = {"scope": "entire harness process, including previously imported modules", "resident_bytes": None, + "peak_resident_bytes": None} + if platform.system() == "Linux": + import resource + memory["peak_resident_bytes"] = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * 1024 + try: + for line in Path("/proc/self/status").read_text().splitlines(): + if line.startswith("VmRSS:"): + memory["resident_bytes"] = int(line.split()[1]) * 1024 + except (OSError, ValueError): + pass + report["process_memory"] = memory + from ..canonical import bytes_digest + module_root = Path(__file__).parent + report["implementation_hashes"] = {name: bytes_digest((module_root / name).read_bytes()) for name in + ("workloads.py", "telemetry.py", "items.py", "service.py", "store.py", "domain_index.py", "domains.py", "security.py", "strategies.py", "fixtures.py")} + report["implementation_hashes"].update({"../" + name: bytes_digest((module_root.parent / name).read_bytes()) for name in + ("backend.py", "constraints.py", "domains.py", "domain_publication.py", "plans.py", "trust.py", "compiler.py", "canonical.py", "demo.py")}) + report["reproduction"] = {"command": "python -m trace_gc domain-workload --output REPORT.json --repetitions " + str(repetitions) + " --workers " + str(workers), + "timings_and_ephemeral_receipt_hashes": "expected to differ between runs"} + if output is not None: + write(Path(output), report) + return report From 081da7e491a5635a983bda8098ba2138687a897d Mon Sep 17 00:00:00 2001 From: Timothy Wayne Gregg Date: Tue, 17 Nov 2026 22:18:06 -0500 Subject: [PATCH 2/2] Complete scheduled workloads and verify historical withdrawal Signed-off-by: Timothy Wayne Gregg --- docs/research_domain_workloads.md | 6 +- tests/test_research_domain_workloads.py | 77 ++++++++++++++++++++- trace_gc/retrieval/workloads.py | 90 ++++++++++++++++++++----- 3 files changed, 152 insertions(+), 21 deletions(-) diff --git a/docs/research_domain_workloads.md b/docs/research_domain_workloads.md index dac8f33..f72154c 100644 --- a/docs/research_domain_workloads.md +++ b/docs/research_domain_workloads.md @@ -17,7 +17,9 @@ The in-memory workers are same-process threads over copies of one immutable refe `WorkloadRecorder`, `QueryCase`, `run_query_workload`, `measure_query` and `measure_publication` are reusable with an application's representative inputs and existing trusted services. The recorder does **not** create ACL grants or approve a publication. The publication wrapper requires ordinary signed preflight/authorization receipts. It reserves bounded telemetry capacity before execution, so capacity exhaustion cannot happen only after a successful write. -Latency uses `perf_counter_ns`; percentiles use nearest rank and always carry sample counts. Queries include consistent authority reads, ACL checks, candidate generation, canonical revalidation and cache handling. Write latency measures the trusted publish/commit call, excluding caller plan preparation/signing. Committed, replayed and rejected publication samples remain distinguishable. +The reusable scheduler continues through recorded retrieval exceptions. Factory and measurement failures, including recorder capacity exhaustion, still fail the schedule. The standalone query measurement records retrieval exceptions and raises them to the caller. + +Latency uses `perf_counter_ns`; percentiles use nearest rank and always carry sample counts. Queries include consistent authority reads, ACL checks, candidate generation, canonical revalidation and cache handling. Write latency measures the trusted publish/commit call, excluding caller plan preparation/signing. Committed, replayed and rejected publication samples remain distinguishable. Wall-clock rates cover in-memory query attempts and completions during the worker schedule, including worker setup and excluding the separate denial. The SQLite mixed-phase rate counts signed committed plans from initialization plan preparation through closure of the second writer connection. Its elapsed time includes index work, queries, retries and withdrawal. The numerator excludes the source-status transaction, replayed plans and rejected attempts. ACL calls are counted by guard; only outermost nested guard wall time is timed, preventing double accounting. Measurement contexts are isolated across threads and reset on exceptions. These are opt-in, process-local observations, not changes to scientific records, snapshot identity or permissions. Instrumentation itself has overhead; no measured production-speed claim is made. @@ -27,7 +29,7 @@ Topology reports incident active original-assertion degrees, quantiles, Gini, an Index observations include serialized source-row bytes, elapsed time and counts of source and membership rows. The harness measures explicit index materialization and rebuild separately through the phase-owned adapter operations. Retrieval remains read-only and distinguishes projection-only reads from verification of a persisted index. Full authority-audit time and SQLite `dbstat` B-tree bytes are also recorded when available. Database/WAL byte counts are not working-set measurements. Linux RSS observations are process-wide snapshots including the harness and imported modules, not an isolated query's allocation or a deployment memory requirement. -Cache hits/misses, invalidated entries and capacity evictions are distinct. A deliberately small cache exercises churn, not a recommended production cache size. Paired quality compares only the same case ID with/without scope; unlabeled path/community quality is reported as unavailable, not perfect. The lexical/vector fixture contains an explicitly authored cross-domain refutation: preserving it is a conformance check, not evidence of real scientific retrieval accuracy. The report tracks whether a structured conflict item carries both assertion IDs separately from whether both evidence IDs were returned. Current withdrawal is tested separately with forbidden-source expectations. +Cache hits/misses, invalidated entries and capacity evictions are distinct. A deliberately small cache exercises churn, not a recommended production cache size. Paired quality compares only the same case ID with/without scope; unlabeled path/community quality is reported as unavailable, not perfect. The lexical/vector fixture contains an explicitly authored cross-domain refutation: preserving it is a conformance check, not evidence of real scientific retrieval accuracy. The report tracks whether a structured conflict item carries both assertion IDs separately from whether both evidence IDs were returned. The withdrawal check pins the most recent classification that matches the biology query, even when the final classification does not. The same historical query must return the source and evidence before withdrawal and exclude the source afterward. The positive control is reported separately from the measured query count. ## Representative-input gate diff --git a/tests/test_research_domain_workloads.py b/tests/test_research_domain_workloads.py index 62077a5..328e948 100644 --- a/tests/test_research_domain_workloads.py +++ b/tests/test_research_domain_workloads.py @@ -17,7 +17,7 @@ from trace_gc.retrieval.security import AccessFilter from trace_gc.retrieval.telemetry import active, measure_retrieval, measured_acl, domain_hop from trace_gc.retrieval.workloads import (QueryCase, WorkloadRecorder, percentiles, topology, measure_query, - measure_publication, run_reference_domain_workload) + measure_publication, run_query_workload, run_reference_domain_workload) from test_research_domain_transactions import DomainFixture @@ -141,6 +141,58 @@ def test_actual_query_measurements_preserve_retrieval_and_do_not_log_source_text self.assertNotIn(c.get(f["evidence"]["e-support"])["quote"], json.dumps(sample)) self.assertEqual(sample["cache_delta"]["hits"], 1) + def test_schedule_continues_after_recorded_rejection_and_error(self): + fixture = domain_corpus() + retriever = fixture["retriever"] + request = query(requesting_component="downstream-search", security_scope=SCOPE, + strategies=["LEXICAL"], text="improves") + denied = QueryCase("denied", {**request, "security_scope": "different-scope"}) + valid = QueryCase("valid", request) + with self.subTest("standalone preserves retrieval exception"): + rows = recorder() + with self.assertRaises(ContractError) as rejected: + measure_query(retriever, denied, rows) + self.assertEqual(rejected.exception.code, "SECURITY_SCOPE") + self.assertEqual(rows.report()["query_outcomes"], {"completed": 0, "rejected_or_error": 1}) + + rows = recorder() + retrieve = retriever.retrieve + + def occasionally_fails(request): + if request["text"] == "synthetic-error": + raise RuntimeError("synthetic adapter failure") + return retrieve(request) + + retriever.retrieve = occasionally_fails + failed = QueryCase("adapter-error", {**request, "text": "synthetic-error"}) + run_query_workload(lambda: retriever, [denied, failed, valid], rows, repetitions=2) + samples = rows.report()["samples"] + self.assertEqual([row["case_id"] for row in samples], ["denied", "adapter-error", "valid"] * 2) + self.assertEqual([row["outcome"] for row in samples[:2]], ["SECURITY_SCOPE", "ERROR"]) + self.assertEqual(rows.report()["query_outcomes"], {"completed": 2, "rejected_or_error": 4}) + + def test_schedule_propagates_capacity_factory_and_measurement_failures(self): + case = QueryCase("case", {}) + workspace = Mock() + workspace._lock = threading.RLock() + workspace.retrieve.side_effect = RuntimeError("synthetic retrieval failure") + rows = recorder(maximum_samples=1) + with self.assertRaises(ContractError) as capacity: + run_query_workload(lambda: workspace, [case, case], rows, repetitions=1) + self.assertEqual(capacity.exception.code, "WORKLOAD_LIMIT") + self.assertEqual(workspace.retrieve.call_count, 1) + self.assertEqual(rows.report()["query_outcomes"], {"completed": 0, "rejected_or_error": 1}) + + with self.assertRaisesRegex(RuntimeError, "factory failure"): + run_query_workload(Mock(side_effect=RuntimeError("factory failure")), [case], recorder()) + workspace.retrieve.side_effect = None + workspace.retrieve.return_value = "result" + workspace.catalog.get.side_effect = RuntimeError("measurement failure") + rows = recorder() + with self.assertRaisesRegex(RuntimeError, "measurement failure"): + run_query_workload(lambda: workspace, [case], rows) + self.assertEqual(rows.report()["sample_count"], 0) + def test_unsigned_publication_fails_and_is_counted_as_rejected_not_written(self): with tempfile.TemporaryDirectory() as directory: f = DomainFixture(directory) @@ -163,6 +215,16 @@ def test_synthetic_smoke_runs_real_reference_writes_indexes_churn_and_cas(self): self.assertEqual(report["input_manifest"]["data_kind"], "SYNTHETIC") self.assertEqual(report["status"], "MEASURED_NOT_QUALIFIED") self.assertEqual(report["sample_count"], 26) + rates = report["phase_rates"] + memory = rates["memory_read_schedule"] + sqlite = rates["sqlite_mixed"] + self.assertGreater(memory["wall_seconds"], 0) + self.assertGreater(sqlite["wall_seconds"], 0) + self.assertEqual((memory["query_attempts"], memory["query_completions"]), (8, 8)) + self.assertAlmostEqual(memory["attempts_per_second"], 8 / memory["wall_seconds"]) + self.assertAlmostEqual(memory["completions_per_second"], 8 / memory["wall_seconds"]) + self.assertEqual(sqlite["committed_signed_plans"], 5) + self.assertAlmostEqual(sqlite["committed_signed_plans_per_second"], 5 / sqlite["wall_seconds"]) # The integrated protocol includes rejected requests and exact identity # implementation pins; neither prior branch's coverage may be discarded. from trace_gc.canonical import bytes_digest @@ -201,3 +263,16 @@ def test_synthetic_smoke_runs_real_reference_writes_indexes_churn_and_cas(self): self.assertIsNone(report["paired_comparison"]["path"]["scoped"]["missing_structured_conflicts"]) self.assertEqual(report["production_graph_writes"], 0) self.assertEqual(report["provider_calls"], 0) + + def test_even_repetitions_prove_withdrawal_on_matching_historical_snapshot(self): + report = run_reference_domain_workload(repetitions=4, workers=1) + control = report["revocation_control"] + self.assertEqual(control["graph_version"] + 1, control["last_classification_graph_version"]) + self.assertTrue(control["source_and_evidence_visible_before_withdrawal"]) + self.assertTrue(control["source_excluded_after_withdrawal"]) + self.assertFalse(control["positive_control_in_query_sample_count"]) + revoked, = (row for row in report["samples"] if row.get("case_id") == "sqlite-historical-current-revocation") + self.assertEqual(revoked["graph_version"], control["graph_version"]) + self.assertEqual(revoked["quality"]["forbidden_sources_returned"], 0) + self.assertEqual(report["query_outcomes"], {"completed": 41, "rejected_or_error": 1}) + self.assertEqual(report["sample_count"], 54) diff --git a/trace_gc/retrieval/workloads.py b/trace_gc/retrieval/workloads.py index d700176..450a6ca 100644 --- a/trace_gc/retrieval/workloads.py +++ b/trace_gc/retrieval/workloads.py @@ -25,7 +25,7 @@ from ..errors import ContractError, require from .telemetry import measure_retrieval -VERSION = "research-domain-workloads-v1.2" +VERSION = "research-domain-workloads-v1.3" REFERENCE_QUERY_TIME = "2026-09-27T00:00:00Z" @@ -212,13 +212,20 @@ def missing_conflict_edges(rows): def measure_query(retriever: Any, case: QueryCase, recorder: WorkloadRecorder) -> str: with recorder.slot() as slot: - return _measure_query(retriever, case, slot) + result = _measure_query(retriever, case, slot, continue_on_query_error=False) + assert result is not None + return result + + +def _returned_sources(catalog, context: dict[str, Any]) -> set[str]: + sources = {source for item in context["items"] for source in item["source_ids"]} + sources.update(catalog.get(ref, "evidence")["source_snapshot_id"] for ref in context["selected_evidence_ids"]) + return sources -def _measure_query(retriever: Any, case: QueryCase, recorder: Any) -> str: +def _measure_query(retriever: Any, case: QueryCase, recorder: Any, *, continue_on_query_error: bool) -> str | None: # Keep the result and its catalog view consistent through observation. with retriever._lock: - result_id = None # Malformed requests still need failure telemetry. Hashing a NaN or # invalid Unicode must not replace the retriever's original exception. try: @@ -231,9 +238,6 @@ def _measure_query(retriever: Any, case: QueryCase, recorder: Any) -> str: with measure_retrieval() as measurements: try: result_id = retriever.retrieve(case.request) - result = retriever.catalog.get(result_id, "retrieval-result") - context = retriever.catalog.get(result["graph_context_id"], "graph-context") - outcome = result["status"] except Exception as exc: # Preserve the exact exception for the caller. Do not log its # message, stack, provider response, or any query/source text. @@ -247,12 +251,16 @@ def _measure_query(retriever: Any, case: QueryCase, recorder: Any) -> str: "adapter_metrics": dict(measurements.read_metrics), "measurements": measurements.as_dict(), "cache_delta": {name: measurements.cache[name] for name in ("hits", "misses", "invalidations", "evictions")}}) + if continue_on_query_error: + return None raise + result = retriever.catalog.get(result_id, "retrieval-result") + context = retriever.catalog.get(result["graph_context_id"], "graph-context") + outcome = result["status"] elapsed = (perf_counter_ns() - started) / 1_000_000 evidence = set(context["selected_evidence_ids"]) conflict_items = [set(item["assertion_ids"]) for item in context["items"] if item["kind"] == "CONFLICT"] - sources = {s for item in context["items"] for s in item["source_ids"]} - sources.update(retriever.catalog.get(ref, "evidence")["source_snapshot_id"] for ref in evidence) + sources = _returned_sources(retriever.catalog, context) scope = case.request.get("research_domain_scope") sample = {"kind": "QUERY", "case_id": case.case_id, "pair_id": case.pair_id, "operation": "query:" + ("scoped:" if scope else "unscoped:") + "+".join(case.request["retrieval_strategy"]), @@ -328,13 +336,15 @@ def _measure_publication(service: Any, catalog: Any, plan_id: str, recorder: Any def run_query_workload(factory: Callable[[], Any], cases: list[QueryCase], recorder: WorkloadRecorder, *, repetitions: int = 3, workers: int = 1) -> None: + """Run every scheduled case, continuing after a recorded retrieval exception.""" require(type(repetitions) is int and repetitions > 0 and type(workers) is int and 1 <= workers <= 32 and bool(cases), "WORKLOAD_INPUT", "nonempty cases, positive repetitions and 1..32 workers required") def execute(worker): retriever = factory() for _ in range(repetitions): for case in cases: - measure_query(retriever, case, recorder) + with recorder.slot() as slot: + _measure_query(retriever, case, slot, continue_on_query_error=True) with ThreadPoolExecutor(max_workers=workers) as pool: list(pool.map(execute, range(workers))) @@ -394,7 +404,11 @@ def factory(): adapter = InMemoryGraphAdapter(copied, fixture["adapter"].snapshot_ids, fixture["adapter"].source_status) return HybridRetriever(adapter, catalog=copied, access_policy=fixture["retriever"].access_policy, cache=RetrievalCache(capacity=4)) + memory_started = perf_counter_ns() run_query_workload(factory, cases, recorder, repetitions=repetitions, workers=workers) + memory_seconds = (perf_counter_ns() - memory_started) / 1e9 + scheduled_query_count = len(recorder.samples) + scheduled_query_completions = sum(row["completed"] for row in recorder.samples) # One separately declared negative case exercises failure cost accounting. # It cannot be included as a successful quality observation or an access grant. try: @@ -434,6 +448,7 @@ def publish(ops, key): result = measure_publication(service, f.catalog, pid, recorder, authorization=auth, preflight=preflight) measure_publication(service, f.catalog, pid, recorder, authorization=auth, preflight=preflight) return result + sqlite_started = perf_counter_ns() publish([migration_operation(operation_id="initialize", reason="Synthetic workload migration")], "workload-initialize") reader = HybridRetriever(SQLiteGraphAdapter(f.backend, audit_trust=f.trust), catalog=f.catalog, access_policy=demo_access(f.catalog, f.backend.snapshot(f.catalog), scope=SCOPE), cache=RetrievalCache(capacity=4)) @@ -454,7 +469,10 @@ def prepare_index(request, *, rebuild=False): assignment = create_assignment(f.catalog, source_snapshot_id=f.source_ids[0], taxonomy_id=taxonomy_id, domain_ids=["research:biology", "research:chemistry"] if revision % 2 else ["research:physics"], classifier_id="synthetic-workload-reviewer", classifier_version=VERSION, review=review, supersedes=previous) - publish([classification_operation(f.catalog, assignment, operation_id="assign")], "workload-assign-" + str(revision)) + publication = publish([classification_operation(f.catalog, assignment, operation_id="assign")], + "workload-assign-" + str(revision)) + if revision % 2: + latest_matching_version = publication["event"]["version"] previous = assignment expected = frozenset({f.evidence_ids[0]}) if revision % 2 else frozenset() case = QueryCase("sqlite-reclassification-" + str(revision), request, expected) @@ -465,12 +483,31 @@ def prepare_index(request, *, rebuild=False): prepare_index(request, rebuild=revision == 1) measure_query(reader, case, recorder) measure_query(reader, case, recorder) - historical_version = f.backend.state()["graph_version"] - f.status_change(f.source_ids[0]) - # A historically matching assignment must still exclude the now-revoked source. - revoked_case = QueryCase("sqlite-historical-current-revocation", {**request, "graph_version": historical_version, - "include_historical": True}, forbidden_source_ids=frozenset({f.source_ids[0]})) - measure_query(reader, revoked_case, recorder) + last_classification_version = publication["event"]["version"] + historical_request = {**request, "graph_version": latest_matching_version, "include_historical": True} + target_source = f.source_ids[0] + + def historical_context(result_id): + context = f.catalog.get(f.catalog.get(result_id, "retrieval-result")["graph_context_id"], "graph-context") + require(context["graph_version"] == latest_matching_version, "WORKLOAD_EXPECTATION", + "withdrawal control selected an unexpected graph version") + return context + + before = historical_context(reader.retrieve(historical_request)) + require(target_source in _returned_sources(f.catalog, before) + and f.evidence_ids[0] in before["selected_evidence_ids"], "WORKLOAD_EXPECTATION", + "historical withdrawal positive control did not return the matching source and evidence") + f.status_change(target_source) + revoked_case = QueryCase("sqlite-historical-current-revocation", historical_request, + forbidden_source_ids=frozenset({target_source})) + after = historical_context(measure_query(reader, revoked_case, recorder)) + require(target_source not in _returned_sources(f.catalog, after), "WORKLOAD_EXPECTATION", + "withdrawn source appeared in historical retrieval") + revocation_control = {"graph_version": latest_matching_version, + "last_classification_graph_version": last_classification_version, + "source_and_evidence_visible_before_withdrawal": True, + "source_excluded_after_withdrawal": True, + "positive_control_in_query_sample_count": False} # Actual concurrent writers against TWO connections to ONE SQLite # authority. The stale loser is recorded, never treated as a write. from ..backend import SQLiteReferenceBackend @@ -507,6 +544,7 @@ def concurrent_publish(job): "WORKLOAD_CONCURRENCY", "exactly one of two same-version writers must commit") finally: concurrent.close() + sqlite_seconds = (perf_counter_ns() - sqlite_started) / 1e9 audit = f.backend.audit(trust=f.trust) sqlite_topology = topology(f.backend.state()) try: @@ -521,8 +559,24 @@ def concurrent_publish(job): finally: f.close() report = recorder.report() + signed_writes = report["writes"]["committed"] + report["phase_rates"] = { + "memory_read_schedule": { + "wall_seconds": memory_seconds, "query_attempts": scheduled_query_count, + "query_completions": scheduled_query_completions, + "attempts_per_second": scheduled_query_count / memory_seconds if memory_seconds else None, + "completions_per_second": scheduled_query_completions / memory_seconds if memory_seconds else None, + "window": "worker pool setup, factories and all paired scheduled queries; excludes the standalone denial", + }, + "sqlite_mixed": { + "wall_seconds": sqlite_seconds, "committed_signed_plans": signed_writes, + "committed_signed_plans_per_second": signed_writes / sqlite_seconds if sqlite_seconds else None, + "window": "initialization plan preparation through writer race and second connection close; includes reads, index work, retries and withdrawal", + }, + } report.update(topology={"memory_read_fixture": topology(snapshot), "sqlite_write_fixture": sqlite_topology}, - sqlite_storage=sizes, index_preparations=index_preparations, cold_projection=cold_projection, sqlite_input_manifest=sqlite_inputs, sqlite_audit=audit, concurrent_write_outcomes=concurrent_outcomes, + sqlite_storage=sizes, index_preparations=index_preparations, cold_projection=cold_projection, + revocation_control=revocation_control, sqlite_input_manifest=sqlite_inputs, sqlite_audit=audit, concurrent_write_outcomes=concurrent_outcomes, provider_calls=0, production_graph_writes=0, placement_decision="DEFERRED_PENDING_REPRESENTATIVE_DATA_OWNER_ISOLATION_AND_SLOS") # Linux process-wide observations, not an isolated workload's memory demand.