diff --git a/README.md b/README.md index cfd5e65..f4ab915 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,8 @@ This release preserves the implemented 0.3 design-review improvements and extend `UpstreamGraphRAG` feeds bounded hybrid context into the existing closure, question, Jev, resolver and mutation workflow. `GraphRAGQueryService` returns source-cited contexts over the compiled graph for search, QA and agents. Both share 18 retrieval channels, strict records, access controls, version-aware caches and budgets; neither grants publication authority. +Both APIs accept a pinned `research_domain_scope` for topical selection while carrying authorized evidence across labels. [Research-domain retrieval](docs/research_domain_retrieval.md) + ```sh python -m trace_gc graphrag-demo --output examples/graphrag/scenarios python -m trace_gc graphrag-benchmark --output benchmarks/graphrag diff --git a/docs/research_domain_retrieval.md b/docs/research_domain_retrieval.md new file mode 100644 index 0000000..c33ec79 --- /dev/null +++ b/docs/research_domain_retrieval.md @@ -0,0 +1,176 @@ +# ACL-safe research-domain retrieval + +Reference implementation for issue #8 in the domain-aware evidence graph initiative. + +## Query contract and distinct scopes + +`research_domain_scope` is an optional, explicitly named field of the versioned +query and retrieval plan. It pins `contract_version: 1`, the immutable taxonomy +ID and hash, canonical domain IDs, `match: ANY | ALL`, `include_unclassified`, +and `include_descendants`. Live scoped queries require the constructor's default +`authorized-identity-v1` conflict-resolution pin. Archived `literal-v1` contexts +and older contexts that omit the pin retain their historical materialization. +Replay can compare one of those contexts with an explicit identity-aware scope. +`research_domain_scope(catalog, taxonomy_id, ids, ...)` +constructs and validates the value. An empty domain list is only meaningful with +`include_unclassified: true`. Unknown or retired IDs and proposed taxonomies +fail closed. Taxonomy review attribution is not a publication signature. + +```python +from trace_gc.retrieval import query +from trace_gc.retrieval.domains import research_domain_scope + +scope = research_domain_scope(catalog, reviewed_taxonomy_id, ["research:biology"]) +request = query(requesting_component="downstream-search", security_scope=tenant, + text="cell culture", strategies=["LEXICAL"], research_domain_scope=scope) +answer = service.query(request) +``` + +Research domains are topical search metadata. They are neither endpoint +`domain`/`range` types, `ontology_scope`, topology-derived `community_scope`, +`source_scope`, nor `security_scope`. No domain assignment creates a source, +node, edge, schema or decision ACL grant. Unscoped old queries and canonical item +bodies retain their previous materialization semantics; adding metadata does +not rewrite any old query, source, evidence or graph-snapshot record. + +The taxonomy pin is exact. Labels in a different taxonomy or version do not +silently share membership, even when strings are equal. A reviewed successor +assignment or a query for the previous version is required. Descendant expansion +is opt-in. `ALL` with descendants means that each requested hierarchy branch has +a matching label, not that a source must have every descendant simultaneously. +An explicit unclassified inclusion also admits missing/retired assignments. + +## Shared admission, not post-filtering graph edges + +`ResearchDomainSelection` is built from a version-consistent read view and its +accepted assignment projection. The application ACL and **present** source +active/READ/non-tombstone state are checked before any assignment is examined +for candidate selection. Missing source authority does not imply unclassified +access. The same predicate is used by canonical materialization and all 18 +strategies, including lexical/vector/source spans, entities, claims, decisions, +hypotheses, schema/ontology rules, graph edges, temporal/provenance channels, +paths, global retrieval and communities. Embedding input consists only of +individually authorized, domain-admitted original evidence spans. + +Assertion membership derives from supporting evidence's exact source snapshots. +Nodes and claims derive membership from authorized incident assertions; shared +identities can participate in several topical views. Only authorized `same_as` +links propagate identity basis. Decisions and hypotheses require their own +source-evidence membership and decision/node ACLs; current in-flight candidates +and their votes are not retrieved as corroboration. Schema rules require a +schema ACL and an authorized selected predicate or endpoint-type basis. A rule +relevant to a selected `Document` type can therefore be retrieved even when its +only existing instance is not a topical anchor; this does not import that +instance as a fact. + +## Atomic explanatory closure + +Topical, relation and source filters constrain **anchors**, not necessary +explanation. An anchor carries its authorized source spans, endpoints, +`same_as` proof, direct `different_from` distinctions and canonical conflicting +or refuting assertions, including sources labeled in another domain or left +unclassified. Relation/source anchor filters and disabling the separate +`CONFLICT` strategy do not silently remove this required closure. Current ACLs +and withdrawal still apply to every closure member. A denied contradiction is +not disclosed; topical scope is not an access override. + +A fact's `prerequisites` are required closure too. The selection follows them +recursively (cycle-safe, depth-unbounded) from every anchor, through sources in +other or no domains, and charges each prerequisite assertion, endpoint and source +span to the same atomic item budget. If any transitive prerequisite is denied, +withdrawn, outside the requested validity window or otherwise unavailable, the +dependent anchor is excluded rather than returned without its proof, and nothing +about the unavailable prerequisite is disclosed. A prerequisite is never an +independent topical hit. Cached closures are keyed by the pinned scope and are +revalidated against current ACL and source status. Tampered closure IDs fail +canonical context validation (`CONTEXT_MATERIALIZATION`). + +Each item's exact `research_domain` metadata distinguishes anchor assertion IDs +from closure assertion IDs, pins scope and classification hashes, and records +source-to-assignment IDs (null for missing assignments). Identity equivalence +proof can be transitive, but `different_from` is only a direct distinction. The +other endpoint's equivalence proof is included without expanding unrelated +`A != B != C` chains. Path hops and community membership use topical assertions. +With `ALL` matching, their combined topical labels can satisfy the scope. +An explicit conflict can carry both sides of the pair while its anchor metadata +identifies the topical members. + +The whole anchor and closure must fit the existing unique-edge, unique-node, +source-span, token, work and time budgets. Otherwise the entire item is dropped +and the result reports partial/budget-limited retrieval. A one-span budget cannot +keep a supporting span while dropping its required refutation. Generated +community summaries remain noncanonical and have no instruction authority. +`community_scope` selects topology-derived component IDs for the queried view. +Changing the edges eligible for traversal can change the component ID. + +## Version binding, current revocation and model contexts + +Snapshot identity and cache keys include the accepted classification revision +and hash, current source status and application ACL. Cached canonical items are +reconstructed against authority on reuse. The planner carries the exact scope +into each query. The read determines the classification identity. Context, +lineage, downstream answers, and replay bind both values. Scoped upstream model +packs carry both values in their traced graph context. Replay validates both +graph versions and their classification revisions against the referenced +contexts. A replay on the same +graph version must resolve to the same immutable snapshot. The replay allowlist +permits an explicit alternative domain scope and preserves the original tenant, +requesting role and candidate. Original observations and evidence hashes remain +immutable. Replay checks current access to both contexts before producing the +receipt. New receipts expose only linked observations whose originating packs +still pass current authorization and whose own decision grants allow access. +The receipt pins the replaying application's authorization record. Validation +checks each preserved hash and binds new observations to authorized receipts +from the replayed result. The comparison is derived from those new observations. + +The reference adapters check live source status before selecting a domain view, +before embeddings, and before returning context. An application-supplied +retrieval token counter also receives only candidates whose sources and access +are still current, including cached candidates and candidates later dropped by +the budget. A changed source epoch requires a new consistent read, and +revocation denies use. Upstream synthesis, reranking and downstream +materialization revalidate context against current ACL/status at their model/use +boundary. Upstream embedding also checks the input candidate's endpoints and +evidence sources. The full candidate and source closure of a retrieval pack is +authorized before token counting and checked before execution and before using +the returned observations. Scoped reads require the present-status hook. +Unscoped adapters that implement the original read-only protocol use their +consistent read status when the hook is absent. +The reference check runs synchronously at each boundary. Deployment-native +revocation propagation, I/O deadlines and cancellation remain #11 acceptance +work. Historical replay of standalone evidence or decisions needs a journal +that records when those records became available. An in-memory fixture without +history can replay snapshot assertions and their evidence closure. + +Pre-scope queries and contexts retain their original fingerprint calculation +when they omit the fields. New contexts pin the classification identity even +when the scope is null, and use a new strategy version. Candidate search, +selection and scoped canonical reconstruction share the discovery work meter. +If verification exhausts it, the service returns a partial result with no +unverified selections. An empty result needs no graph reconstruction. Separate +live use checks have their own bounded verification. Adapter I/O and archival +verification have separate operational timing from candidate search. + +Only canonical selected graph context reaches the model. Its classification +identity and scope have exact field traces. Classification review basis is not +silently promoted into scientific evidence or the Minimum Evidence Closure. +The full accepted graph remains available to deterministic compilation, +identity/constraint validation, publication and audit independently of this +search view. + +## Local conformance + +`tests/test_research_domain_retrieval.py` includes a strategy matrix that +requires each of the 18 strategies to produce its own correctly typed positive +result and checks an unrelated-domain negative for every strategy; automatic +conflict fallback cannot satisfy an otherwise empty channel. Additional cases +inspect actual embedding inputs, real compiler/adapter observation records, +current ACL/withdrawal, reclassification identity, atomic refutation budgets, +cache/plugin tampering, source/relation-filter closure, explicit unclassified +material, taxonomy hierarchy/version pins, planner, upstream and replay bindings. + +The corpus and all classification/reviewer/response labels in these tests are +explicitly fabricated reference fixtures. They are not independent research +labels, representative query quality, authenticated deployment publication or +operational qualification. Run the full release and packaged-wheel gates before +claiming issue completion, and retain #6's exact pinned-legacy external gate. diff --git a/schemas/runtime/classification-read-identity.schema.json b/schemas/runtime/classification-read-identity.schema.json new file mode 100644 index 0000000..7c8eddc --- /dev/null +++ b/schemas/runtime/classification-read-identity.schema.json @@ -0,0 +1,29 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:trace-gc:0.3.0:classification-read-identity", + "title": "TRACE-GC classification-read-identity v0.3.0", + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "revision": { + "type": "integer", + "minimum": 0 + }, + "hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "migrated": { + "type": "boolean" + } + }, + "required": [ + "contract_version", + "revision", + "hash", + "migrated" + ], + "additionalProperties": false +} diff --git a/schemas/runtime/graph-context.schema.json b/schemas/runtime/graph-context.schema.json index 9d0b3a5..bc95939 100644 --- a/schemas/runtime/graph-context.schema.json +++ b/schemas/runtime/graph-context.schema.json @@ -282,6 +282,61 @@ }, "instruction_authority": { "const": false + }, + "research_domain": { + "type": "object", + "properties": { + "version": { + "const": "authorized-research-domain-selection-v1" + }, + "scope_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "classification_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "anchor_assertion_ids": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "uniqueItems": true + }, + "closure_assertion_ids": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "uniqueItems": true + }, + "source_assignments": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "type": "null" + } + ] + } + } + }, + "required": [ + "version", + "scope_hash", + "classification_hash", + "anchor_assertion_ids", + "closure_assertion_ids", + "source_assignments" + ], + "additionalProperties": false } }, "required": [ @@ -487,6 +542,92 @@ "reranking_base_context_id": { "type": "string", "minLength": 1 + }, + "research_domain_scope": { + "anyOf": [ + { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "taxonomy_id": { + "type": "string", + "minLength": 1 + }, + "taxonomy_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "domain_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^research:[a-z0-9][a-z0-9._-]*$" + }, + "uniqueItems": true, + "maxItems": 100 + }, + "match": { + "enum": [ + "ANY", + "ALL" + ] + }, + "include_unclassified": { + "type": "boolean" + }, + "include_descendants": { + "type": "boolean" + }, + "conflict_resolution": { + "enum": [ + "literal-v1", + "authorized-identity-v1" + ] + } + }, + "required": [ + "contract_version", + "taxonomy_id", + "taxonomy_hash", + "domain_ids", + "match", + "include_unclassified", + "include_descendants" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "classification_identity": { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "revision": { + "type": "integer", + "minimum": 0 + }, + "hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "migrated": { + "type": "boolean" + } + }, + "required": [ + "contract_version", + "revision", + "hash", + "migrated" + ], + "additionalProperties": false } }, "required": [ diff --git a/schemas/runtime/graphrag-answer.schema.json b/schemas/runtime/graphrag-answer.schema.json index 7bd63a0..a41af4c 100644 --- a/schemas/runtime/graphrag-answer.schema.json +++ b/schemas/runtime/graphrag-answer.schema.json @@ -239,6 +239,61 @@ }, "instruction_authority": { "const": false + }, + "research_domain": { + "type": "object", + "properties": { + "version": { + "const": "authorized-research-domain-selection-v1" + }, + "scope_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "classification_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "anchor_assertion_ids": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "uniqueItems": true + }, + "closure_assertion_ids": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "uniqueItems": true + }, + "source_assignments": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "type": "null" + } + ] + } + } + }, + "required": [ + "version", + "scope_hash", + "classification_hash", + "anchor_assertion_ids", + "closure_assertion_ids", + "source_assignments" + ], + "additionalProperties": false } }, "required": [ @@ -331,6 +386,92 @@ "created_at": { "type": "string", "format": "date-time" + }, + "research_domain_scope": { + "anyOf": [ + { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "taxonomy_id": { + "type": "string", + "minLength": 1 + }, + "taxonomy_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "domain_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^research:[a-z0-9][a-z0-9._-]*$" + }, + "uniqueItems": true, + "maxItems": 100 + }, + "match": { + "enum": [ + "ANY", + "ALL" + ] + }, + "include_unclassified": { + "type": "boolean" + }, + "include_descendants": { + "type": "boolean" + }, + "conflict_resolution": { + "enum": [ + "literal-v1", + "authorized-identity-v1" + ] + } + }, + "required": [ + "contract_version", + "taxonomy_id", + "taxonomy_hash", + "domain_ids", + "match", + "include_unclassified", + "include_descendants" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "classification_identity": { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "revision": { + "type": "integer", + "minimum": 0 + }, + "hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "migrated": { + "type": "boolean" + } + }, + "required": [ + "contract_version", + "revision", + "hash", + "migrated" + ], + "additionalProperties": false } }, "required": [ diff --git a/schemas/runtime/research-domain-scope.schema.json b/schemas/runtime/research-domain-scope.schema.json new file mode 100644 index 0000000..4059738 --- /dev/null +++ b/schemas/runtime/research-domain-scope.schema.json @@ -0,0 +1,56 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:trace-gc:0.3.0:research-domain-scope", + "title": "TRACE-GC research-domain-scope v0.3.0", + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "taxonomy_id": { + "type": "string", + "minLength": 1 + }, + "taxonomy_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "domain_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^research:[a-z0-9][a-z0-9._-]*$" + }, + "uniqueItems": true, + "maxItems": 100 + }, + "match": { + "enum": [ + "ANY", + "ALL" + ] + }, + "include_unclassified": { + "type": "boolean" + }, + "include_descendants": { + "type": "boolean" + }, + "conflict_resolution": { + "enum": [ + "literal-v1", + "authorized-identity-v1" + ] + } + }, + "required": [ + "contract_version", + "taxonomy_id", + "taxonomy_hash", + "domain_ids", + "match", + "include_unclassified", + "include_descendants" + ], + "additionalProperties": false +} diff --git a/schemas/runtime/retrieval-lineage.schema.json b/schemas/runtime/retrieval-lineage.schema.json index 5476cce..7bafdd1 100644 --- a/schemas/runtime/retrieval-lineage.schema.json +++ b/schemas/runtime/retrieval-lineage.schema.json @@ -253,6 +253,92 @@ "created_at": { "type": "string", "format": "date-time" + }, + "research_domain_scope": { + "anyOf": [ + { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "taxonomy_id": { + "type": "string", + "minLength": 1 + }, + "taxonomy_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "domain_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^research:[a-z0-9][a-z0-9._-]*$" + }, + "uniqueItems": true, + "maxItems": 100 + }, + "match": { + "enum": [ + "ANY", + "ALL" + ] + }, + "include_unclassified": { + "type": "boolean" + }, + "include_descendants": { + "type": "boolean" + }, + "conflict_resolution": { + "enum": [ + "literal-v1", + "authorized-identity-v1" + ] + } + }, + "required": [ + "contract_version", + "taxonomy_id", + "taxonomy_hash", + "domain_ids", + "match", + "include_unclassified", + "include_descendants" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "classification_identity": { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "revision": { + "type": "integer", + "minimum": 0 + }, + "hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "migrated": { + "type": "boolean" + } + }, + "required": [ + "contract_version", + "revision", + "hash", + "migrated" + ], + "additionalProperties": false } }, "required": [ diff --git a/schemas/runtime/retrieval-plan.schema.json b/schemas/runtime/retrieval-plan.schema.json index ff62cc0..0bac34e 100644 --- a/schemas/runtime/retrieval-plan.schema.json +++ b/schemas/runtime/retrieval-plan.schema.json @@ -198,6 +198,66 @@ "created_at": { "type": "string", "format": "date-time" + }, + "research_domain_scope": { + "anyOf": [ + { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "taxonomy_id": { + "type": "string", + "minLength": 1 + }, + "taxonomy_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "domain_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^research:[a-z0-9][a-z0-9._-]*$" + }, + "uniqueItems": true, + "maxItems": 100 + }, + "match": { + "enum": [ + "ANY", + "ALL" + ] + }, + "include_unclassified": { + "type": "boolean" + }, + "include_descendants": { + "type": "boolean" + }, + "conflict_resolution": { + "enum": [ + "literal-v1", + "authorized-identity-v1" + ] + } + }, + "required": [ + "contract_version", + "taxonomy_id", + "taxonomy_hash", + "domain_ids", + "match", + "include_unclassified", + "include_descendants" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] } }, "required": [ diff --git a/schemas/runtime/retrieval-query.schema.json b/schemas/runtime/retrieval-query.schema.json index 5bda4f5..d391acb 100644 --- a/schemas/runtime/retrieval-query.schema.json +++ b/schemas/runtime/retrieval-query.schema.json @@ -300,6 +300,66 @@ "created_at": { "type": "string", "format": "date-time" + }, + "research_domain_scope": { + "anyOf": [ + { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "taxonomy_id": { + "type": "string", + "minLength": 1 + }, + "taxonomy_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "domain_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^research:[a-z0-9][a-z0-9._-]*$" + }, + "uniqueItems": true, + "maxItems": 100 + }, + "match": { + "enum": [ + "ANY", + "ALL" + ] + }, + "include_unclassified": { + "type": "boolean" + }, + "include_descendants": { + "type": "boolean" + }, + "conflict_resolution": { + "enum": [ + "literal-v1", + "authorized-identity-v1" + ] + } + }, + "required": [ + "contract_version", + "taxonomy_id", + "taxonomy_hash", + "domain_ids", + "match", + "include_unclassified", + "include_descendants" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] } }, "required": [ diff --git a/schemas/runtime/retrieval-replay.schema.json b/schemas/runtime/retrieval-replay.schema.json index a03c3d7..ec69913 100644 --- a/schemas/runtime/retrieval-replay.schema.json +++ b/schemas/runtime/retrieval-replay.schema.json @@ -83,6 +83,182 @@ "created_at": { "type": "string", "format": "date-time" + }, + "replay_access_id": { + "type": "string", + "minLength": 1 + }, + "original_classification_identity": { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "revision": { + "type": "integer", + "minimum": 0 + }, + "hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "migrated": { + "type": "boolean" + } + }, + "required": [ + "contract_version", + "revision", + "hash", + "migrated" + ], + "additionalProperties": false + }, + "replayed_classification_identity": { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "revision": { + "type": "integer", + "minimum": 0 + }, + "hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "migrated": { + "type": "boolean" + } + }, + "required": [ + "contract_version", + "revision", + "hash", + "migrated" + ], + "additionalProperties": false + }, + "original_research_domain_scope": { + "anyOf": [ + { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "taxonomy_id": { + "type": "string", + "minLength": 1 + }, + "taxonomy_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "domain_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^research:[a-z0-9][a-z0-9._-]*$" + }, + "uniqueItems": true, + "maxItems": 100 + }, + "match": { + "enum": [ + "ANY", + "ALL" + ] + }, + "include_unclassified": { + "type": "boolean" + }, + "include_descendants": { + "type": "boolean" + }, + "conflict_resolution": { + "enum": [ + "literal-v1", + "authorized-identity-v1" + ] + } + }, + "required": [ + "contract_version", + "taxonomy_id", + "taxonomy_hash", + "domain_ids", + "match", + "include_unclassified", + "include_descendants" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "replayed_research_domain_scope": { + "anyOf": [ + { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "taxonomy_id": { + "type": "string", + "minLength": 1 + }, + "taxonomy_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "domain_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^research:[a-z0-9][a-z0-9._-]*$" + }, + "uniqueItems": true, + "maxItems": 100 + }, + "match": { + "enum": [ + "ANY", + "ALL" + ] + }, + "include_unclassified": { + "type": "boolean" + }, + "include_descendants": { + "type": "boolean" + }, + "conflict_resolution": { + "enum": [ + "literal-v1", + "authorized-identity-v1" + ] + } + }, + "required": [ + "contract_version", + "taxonomy_id", + "taxonomy_hash", + "domain_ids", + "match", + "include_unclassified", + "include_descendants" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] } }, "required": [ @@ -102,5 +278,86 @@ "authorization_granted", "created_at" ], - "additionalProperties": false + "additionalProperties": false, + "allOf": [ + { + "if": { + "required": [ + "replay_access_id" + ] + }, + "then": { + "properties": { + "synthesis_comparison": { + "oneOf": [ + { + "type": "object", + "properties": { + "observation_ids": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "uniqueItems": true + } + }, + "required": [ + "observation_ids" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "status": { + "const": "NOT_RUN" + }, + "reason": { + "const": "No synthesis executor supplied." + } + }, + "required": [ + "status", + "reason" + ], + "additionalProperties": false + } + ] + } + } + } + }, + { + "if": { + "anyOf": [ + { + "required": [ + "original_classification_identity" + ] + }, + { + "required": [ + "original_research_domain_scope" + ] + }, + { + "required": [ + "replayed_classification_identity" + ] + }, + { + "required": [ + "replayed_research_domain_scope" + ] + } + ] + }, + "then": { + "required": [ + "replay_access_id" + ] + } + } + ] } diff --git a/tests/test_graphrag_pipeline.py b/tests/test_graphrag_pipeline.py index 5d5c674..82dcbff 100644 --- a/tests/test_graphrag_pipeline.py +++ b/tests/test_graphrag_pipeline.py @@ -18,7 +18,7 @@ from trace_gc.retrieval.service import HybridRetriever, GraphRAGQueryService, validate_context from trace_gc.retrieval.planner import RetrievalPlanner, UpstreamGraphRAG from trace_gc.retrieval.reranker import JevReranker -from trace_gc.retrieval.integration import validate_record +from trace_gc.retrieval.integration import references, validate_record from trace_gc.validation import validate_bundle from trace_gc.replay import replay_retrieval @@ -260,9 +260,40 @@ def test_replay_preserves_original_model_receipts(self): pack, ref = self.retrieved_pack() obs = record_response(self.c, pack, fixture_response(self.c.get(pack, "pack")))[0] before = self.c.hash(obs) - replay = replay_retrieval(self.r, ref, {"retrieval_strategy": ["SOURCE"]}) + unrelated_pack = compile_pack(self.c, id_="unrelated-replay-pack", run_id=RUN, + candidate_ids=self.f.candidate_ids, questions=[question(self.f.candidate_ids[0], id_="standalone")], + snapshot_id=self.f.snapshot_id, security_scope=SCOPE) + unrelated = record_response(self.c, unrelated_pack, fixture_response(self.c.get(unrelated_pack, "pack")))[0] + self.r.set_access_policy(demo_access(self.c, self.f.snapshot_id, scope=SCOPE)) + + def synthesize(result_id): + context_id = self.c.get(result_id, "retrieval-result")["graph_context_id"] + new_pack = compile_pack(self.c, id_="counterfactual-replay-pack", run_id=RUN, + candidate_ids=self.f.candidate_ids, questions=[question(self.f.candidate_ids[0], id_="replayed")], + snapshot_id=self.f.snapshot_id, security_scope=SCOPE, + graph_context_ids=[context_id], source_retrieval_ids=[result_id]) + observations = record_response(self.c, new_pack, fixture_response(self.c.get(new_pack, "pack"))) + self.r.set_access_policy(demo_access(self.c, self.f.snapshot_id, scope=SCOPE)) + return {"observation_ids": observations, "other": {"observations": [unrelated]}} + + replay = replay_retrieval(self.r, ref, {"retrieval_strategy": ["SOURCE"]}, synthesize=synthesize) self.assertEqual(self.c.hash(obs), before) self.assertEqual(self.c.get(replay, "retrieval-replay")["observation_hashes_preserved"][obs], before) + receipt = self.c.get(replay, "retrieval-replay") + validate_record(self.c, self.c.record(replay)) + self.assertEqual(receipt["observation_hashes_preserved"], {obs: before}) + self.assertEqual(receipt["new_observation_ids"], receipt["synthesis_comparison"]["observation_ids"]) + self.assertEqual(set(receipt["synthesis_comparison"]), {"observation_ids"}) + undecorated = deepcopy(receipt) + undecorated["synthesis_comparison"]["observation_ids"].append(unrelated) + with self.assertRaisesRegex(ContractError, "REPLAY_OBSERVATION_LINEAGE"): + validate_record(self.c, {"kind": "retrieval-replay", "body": undecorated}) + refs = references("retrieval-replay", receipt) + self.assertIn((obs, "observation"), refs) + self.assertNotIn((unrelated, "observation"), refs) + receipt["observation_hashes_preserved"][obs] = "0" * 64 + with self.assertRaisesRegex(ContractError, "REPLAY_OBSERVATION_LINEAGE"): + validate_record(self.c, self.c.record(self.c.put("retrieval-replay", receipt))) def test_summary_cannot_be_substituted_for_source_evidence(self): _, ref = self.retrieved_pack() diff --git a/tests/test_research_domain_identity_conflicts.py b/tests/test_research_domain_identity_conflicts.py new file mode 100644 index 0000000..9840fc1 --- /dev/null +++ b/tests/test_research_domain_identity_conflicts.py @@ -0,0 +1,272 @@ +"""Synthetic, authority-bound identity/refutation regressions (not corpus quality).""" +from copy import deepcopy +import unittest +from unittest.mock import patch + +from trace_gc.constraints import validate_graph +from trace_gc.errors import ContractError +from trace_gc.replay import replay_retrieval +from trace_gc.retrieval.contracts import RetrievalBudget, query +from trace_gc.retrieval.domains import research_domain_scope +from trace_gc.retrieval.fixtures import domain_corpus, demo_access, SCOPE +from trace_gc.retrieval.items import conflict_pairs +from trace_gc.retrieval.service import HybridRetriever, validate_context +from trace_gc.retrieval.store import InMemoryGraphAdapter + + +class IdentityConflictTests(unittest.TestCase): + def setUp(self): + self.f = domain_corpus() + self.c = self.f['catalog'] + self.original = self.f['claim_id'] + self.alias = self.c.claim('Alternative identifier for the synthetic intervention claim.') + self.snapshot = self.c.get(self.f['snapshot_id'], 'graph-snapshot') + self.snapshot['nodes'][self.alias] = 'Claim' + self.snapshot['assertions']['e-refute']['assertion']['object'] = self.alias + self.statuses = deepcopy(self.f['statuses']) + self.identity_source = self.c.source('synthetic-claim-identity', '1', + 'Synthetic fixture: the two claim IDs denote the same research question.', scope=SCOPE) + evidence = self.c.evidence(self.identity_source) + self.identity_evidence = evidence + self.statuses[self.identity_source] = {'active': True, 'permission': 'READ', 'epoch': 1, + 'updated_at': '2026-09-27T00:00:00Z', 'tombstone': False} + self.snapshot['source_epochs'][self.identity_source] = 1 + self.snapshot['assertions']['e-claim-identity'] = { + 'assertion': {'subject': self.original, 'predicate': 'same_as', 'object': self.alias, 'qualifiers': {}}, + 'evidence_ids': [evidence], 'prerequisites': [], 'active': True, 'revision': 1} + self.scope = research_domain_scope(self.c, self.f['taxonomy_id'], ['research:biology']) + self.budget = RetrievalBudget(maximum_tokens=150000, maximum_latency_ms=20000, + maximum_edges=100, maximum_nodes=100, maximum_source_spans=100) + self.refresh() + + def refresh(self): + # Distinct paper subjects allow contradictory evidence without violating + # the authority's graph-wide incompatible-relation constraint. + validate_graph(self.snapshot['nodes'], self.snapshot['assertions'], + self.c.get(self.snapshot['schema_id'], 'schema')['relations']) + self.snapshot_id = self.c.put('graph-snapshot', self.snapshot) + self.adapter = InMemoryGraphAdapter(self.c, [self.snapshot_id], self.statuses) + self.retriever = HybridRetriever(self.adapter, catalog=self.c, + access_policy=demo_access(self.c, self.snapshot_id)) + + def request(self, **changes): + return query(requesting_component='downstream-identity-regression', security_scope=SCOPE, + text=changes.pop('text', 'improves'), strategies=changes.pop('strategies', ['LEXICAL']), + include_conflicts=False, research_domain_scope=changes.pop('research_domain_scope', self.scope), + budget=changes.pop('budget', self.budget), **changes) + + def retrieve(self, **changes): + result = self.c.get(self.retriever.retrieve(self.request(**changes)), 'retrieval-result') + context = self.c.get(result['graph_context_id'], 'graph-context') + validate_context(self.c, result['graph_context_id'], current_access=self.retriever.access_policy, + current_status=self.adapter.current_source_status()) + return result, context + + def test_aliased_refutation_and_its_identity_proof_are_atomic_closure(self): + _, context = self.retrieve() + self.assertEqual(len(context['items']), 1) + item = context['items'][0] + self.assertTrue({'e-support', 'e-refute', 'e-claim-identity'} <= set(item['assertion_ids'])) + self.assertEqual(item['trust_class'], 'CONFLICTED_GRAPH_FACT') + self.assertIn(self.f['evidence']['e-refute'], item['evidence_ids']) + self.assertIn(self.identity_evidence, item['evidence_ids']) + # The identity source is explicitly unclassified, not granted a label. + self.assertIsNone(item['research_domain']['source_assignments'][self.identity_source]) + + def test_denied_identity_does_not_invent_a_conflict_or_leak_evidence(self): + policy = deepcopy(self.retriever.access_policy) + del policy['grants']['source:' + self.identity_source] + self.retriever.set_access_policy(policy) + _, context = self.retrieve() + self.assertEqual(set(context['retrieved_edges']), {'e-support'}) + self.assertNotIn(self.identity_evidence, context['selected_evidence_ids']) + self.assertNotIn(self.f['evidence']['e-refute'], context['selected_evidence_ids']) + + def test_inactive_identity_is_not_a_current_equivalence_or_membership_grant(self): + self.snapshot['assertions']['e-claim-identity']['active'] = False + self.refresh() + _, context = self.retrieve(include_historical=True) + self.assertEqual(set(context['retrieved_edges']), {'e-support'}) + + def test_transitive_identity_proofs_retain_cross_domain_refutation(self): + middle = self.c.claim('Intermediate identifier for the synthetic intervention claim.') + self.snapshot['nodes'][middle] = 'Claim' + self.snapshot['assertions']['e-claim-identity']['assertion']['object'] = middle + second = deepcopy(self.snapshot['assertions']['e-claim-identity']) + second['assertion'].update(subject=middle, object=self.alias) + self.snapshot['assertions']['e-claim-identity-2'] = second + self.refresh() + _, context = self.retrieve() + self.assertTrue({'e-support', 'e-refute', 'e-claim-identity', 'e-claim-identity-2'} <= + set(context['items'][0]['assertion_ids'])) + + def test_current_identity_revocation_invalidates_cache_and_old_context(self): + original, context = self.retrieve() + self.assertIn('e-refute', context['retrieved_edges']) + self.retrieve() + self.assertEqual(self.retriever.cache.hits, 1) + self.adapter.source_status[self.identity_source].update(active=False, epoch=2) + _, revoked = self.retrieve() + self.assertEqual(set(revoked['retrieved_edges']), {'e-support'}) + self.assertGreater(self.retriever.cache.invalidations, 0) + with self.assertRaises(ContractError): + validate_context(self.c, original['graph_context_id'], current_access=self.retriever.access_policy, + current_status=self.adapter.current_source_status()) + + def test_denied_refutation_does_not_leak_via_an_authorized_alias(self): + policy = deepcopy(self.retriever.access_policy) + del policy['grants']['source:' + self.f['sources']['e-refute']] + self.retriever.set_access_policy(policy) + _, context = self.retrieve() + self.assertEqual(set(context['retrieved_edges']), {'e-support', 'e-claim-identity'}) + self.assertNotIn(self.f['evidence']['e-refute'], context['selected_evidence_ids']) + self.assertNotEqual(context['items'][0]['trust_class'], 'CONFLICTED_GRAPH_FACT') + + def test_inactive_identity_cannot_give_an_alias_node_topical_membership(self): + self.snapshot['assertions']['e-claim-identity']['active'] = False + self.refresh() + _, context = self.retrieve(strategies=['ENTITY'], text='', focus_entities=[self.alias], include_historical=True) + self.assertEqual(context['items'], []) + + def test_budget_rejects_entire_anchor_rather_than_dropping_alias_refutation(self): + from dataclasses import replace + for budget in (replace(self.budget, maximum_edges=2), replace(self.budget, maximum_source_spans=2)): + with self.subTest(budget=budget): + result, context = self.retrieve(budget=budget) + self.assertEqual(result['status'], 'PARTIAL') + self.assertEqual(context['items'], []) + self.assertEqual(context['selected_evidence_ids'], []) + + def test_tampering_with_required_aliased_refutation_fails_canonical_validation(self): + result, context = self.retrieve() + context['items'][0]['assertion_ids'].remove('e-refute') + forged = self.c.put('graph-context', context) + with self.assertRaises(ContractError) as caught: + validate_context(self.c, forged, current_access=self.retriever.access_policy, + current_status=self.adapter.current_source_status()) + self.assertEqual(caught.exception.code, 'CONTEXT_MATERIALIZATION') + + def test_schema_inverse_form_of_refutation_is_not_hidden(self): + from trace_gc.demo import relation + schema = self.c.get(self.snapshot['schema_id'], 'schema') + schema['relations']['is_refuted_by'] = relation('Claim', 'Document', inverse_of='refutes') + schema['version'] = 'synthetic-inverse-refutation-v1' + schema_id = self.c.put('schema', schema) + self.snapshot.update(schema_id=schema_id, schema_hash=self.c.hash(schema_id)) + a = self.snapshot['assertions']['e-refute']['assertion'] + a.update(subject=self.alias, predicate='is_refuted_by', object='Paper-B') + self.refresh() + _, context = self.retrieve() + self.assertIn('e-refute', context['retrieved_edges']) + self.assertEqual(context['items'][0]['trust_class'], 'CONFLICTED_GRAPH_FACT') + # The original inverse assertion and source span are kept, not rewritten. + self.assertEqual(self.c.get(self.snapshot_id)['assertions']['e-refute']['assertion'], a) + + def test_inverse_identity_keeps_the_actual_proof_record(self): + from trace_gc.demo import relation + schema = self.c.get(self.snapshot['schema_id'], 'schema') + schema['relations']['alias_of'] = relation('*', '*', inverse_of='same_as') + schema['version'] = 'synthetic-inverse-identity-v1' + schema_id = self.c.put('schema', schema) + self.snapshot.update(schema_id=schema_id, schema_hash=self.c.hash(schema_id)) + a = self.snapshot['assertions']['e-claim-identity']['assertion'] + a.update(subject=self.alias, predicate='alias_of', object=self.original) + self.refresh() + _, context = self.retrieve() + self.assertTrue({'e-support', 'e-refute', 'e-claim-identity'} <= set(context['retrieved_edges'])) + self.assertIn(self.identity_evidence, context['selected_evidence_ids']) + + def test_disjoint_intervals_do_not_create_alias_conflicts(self): + self.snapshot['assertions']['e-support']['assertion']['qualifiers']['valid_until'] = '2024-01-01T00:00:00Z' + self.snapshot['assertions']['e-refute']['assertion']['qualifiers']['valid_from'] = '2024-01-01T00:00:00Z' + self.refresh() + _, context = self.retrieve() + self.assertNotIn('e-refute', context['retrieved_edges']) + self.assertNotEqual(context['items'][0]['trust_class'], 'CONFLICTED_GRAPH_FACT') + + def test_vector_inputs_remain_scoped_but_output_retains_alias_conflict(self): + class Spy: + version = 'synthetic-identity-embedding-spy-v1' + def __init__(self): + self.seen = [] + def embed(self, texts): + self.seen.extend(texts) + return [[1.0, 0.0] for text in texts] + spy = Spy() + self.retriever.embedding = spy + _, context = self.retrieve(strategies=['VECTOR']) + self.assertNotIn(self.c.get(self.f['evidence']['e-refute'])['quote'], spy.seen) + self.assertNotIn(self.c.get(self.identity_evidence)['quote'], spy.seen) + self.assertIn('e-refute', context['retrieved_edges']) + self.assertIn(self.identity_evidence, context['selected_evidence_ids']) + + def test_missing_legacy_pin_preserves_old_materialization_and_can_be_compared(self): + legacy = deepcopy(self.scope) + legacy.pop('conflict_resolution') + with self.assertRaisesRegex(ContractError, 'RESEARCH_DOMAIN_SCOPE'): + self.retrieve(research_domain_scope=legacy) + # Generate the archived fixture with the historical materialization path. + with patch('trace_gc.retrieval.service.require_live_scope'): + old, old_context = self.retrieve(research_domain_scope=legacy) + self.assertEqual(set(old_context['retrieved_edges']), {'e-support', 'e-claim-identity'}) + self.assertIn('LEGACY_LITERAL_CONFLICT_RESOLUTION_MAY_OMIT_ALIASED_REFUTATIONS', old['warnings']) + before = self.c.hash(old['graph_context_id']) + new, new_context = self.retrieve() + self.assertIn('e-refute', new_context['retrieved_edges']) + self.assertNotEqual(old_context['retrieval_fingerprint'], new_context['retrieval_fingerprint']) + validate_context(self.c, old['graph_context_id'], current_access=self.retriever.access_policy, + current_status=self.adapter.current_source_status()) + self.assertEqual(self.c.hash(old['graph_context_id']), before) + explicit = research_domain_scope(self.c, self.f['taxonomy_id'], ['research:biology'], conflict_resolution='literal-v1') + with self.assertRaisesRegex(ContractError, 'RESEARCH_DOMAIN_SCOPE'): + self.retrieve(research_domain_scope=explicit) + with patch('trace_gc.retrieval.service.require_live_scope'): + _, explicit_context = self.retrieve(research_domain_scope=explicit) + self.assertEqual(explicit_context['retrieved_edges'], old_context['retrieved_edges']) + + def test_unknown_algorithm_pin_is_rejected(self): + with self.assertRaises(ContractError): + research_domain_scope(self.c, self.f['taxonomy_id'], ['research:biology'], conflict_resolution='latest') + + def test_counterfactual_replay_keeps_original_literal_scope_immutable(self): + legacy = deepcopy(self.scope) + legacy.pop('conflict_resolution') + with patch('trace_gc.retrieval.service.require_live_scope'): + original_id = self.retriever.retrieve(self.request(research_domain_scope=legacy)) + original_hash = self.c.hash(original_id) + # Explicit synthetic availability journal for this exact read snapshot. + self.adapter.events = [{'version': self.snapshot['graph_version'], 'state_after': self.snapshot, + 'committed_at': '2026-09-27T00:00:00Z', 'record_hashes': {r['id']: r['hash'] for r in self.c.all()}}] + replay_id = replay_retrieval(self.retriever, original_id, {'research_domain_scope': self.scope}) + replay = self.c.get(replay_id, 'retrieval-replay') + self.assertEqual(replay['original_research_domain_scope'], legacy) + self.assertEqual(replay['replayed_research_domain_scope'], self.scope) + self.assertEqual(replay['original_classification_identity'], replay['replayed_classification_identity']) + self.assertFalse(replay['authorization_granted']) + self.assertEqual(self.c.hash(original_id), original_hash) + result = self.c.get(replay['replayed_result_id'], 'retrieval-result') + context = self.c.get(result['graph_context_id'], 'graph-context') + self.assertIn('e-refute', context['retrieved_edges']) + + +class ConflictNormalizationTests(unittest.TestCase): + def test_symmetric_pairs_use_schema_normal_form_only_when_pinned(self): + from trace_gc.demo import relation + schema = {'related': relation('Entity', 'Entity', symmetric=True, incompatible=['unrelated']), + 'unrelated': relation('Entity', 'Entity', symmetric=True, incompatible=['related'])} + def fact(s, p, o): + return {'assertion': {'subject': s, 'predicate': p, 'object': o, 'qualifiers': {}}, 'active': True} + edges = {'left': fact('a', 'related', 'b'), 'right': fact('b', 'unrelated', 'a')} + self.assertEqual(conflict_pairs(edges, schema), []) + self.assertEqual(conflict_pairs(edges, schema, resolve_identities=True), [['left', 'right']]) + + def test_identity_normalization_is_charged_to_work_budget(self): + from trace_gc.demo import relation + from trace_gc.retrieval.budget import BudgetMeter + schema = {'same_as': relation('Entity', 'Entity', symmetric=True, transitive=True)} + edges = {'identity-' + str(i): {'assertion': {'subject': str(i), 'predicate': 'same_as', + 'object': str(i+1), 'qualifiers': {}}, 'active': True} for i in range(20)} + meter = BudgetMeter(RetrievalBudget(maximum_cost_units=10)) + with self.assertRaises(ContractError) as caught: + conflict_pairs(edges, schema, meter, resolve_identities=True) + self.assertEqual(caught.exception.code, 'RETRIEVAL_BUDGET_EXHAUSTED') diff --git a/tests/test_research_domain_prerequisite_closure.py b/tests/test_research_domain_prerequisite_closure.py new file mode 100644 index 0000000..64939f4 --- /dev/null +++ b/tests/test_research_domain_prerequisite_closure.py @@ -0,0 +1,188 @@ +"""Synthetic regressions: required fact prerequisites travel with an in-domain anchor. + +The fixture classifies only the anchor's own sources; the prerequisite chain comes +from unclassified sources, so it can only enter a result as authorized required +closure, never as an independent topical hit. +""" +from copy import deepcopy +from dataclasses import replace +import unittest +from unittest.mock import patch + +from trace_gc.constraints import validate_graph +from trace_gc.errors import ContractError +from trace_gc.retrieval.contracts import RetrievalBudget, query +from trace_gc.retrieval.domains import research_domain_scope +from trace_gc.retrieval.fixtures import domain_corpus, demo_access, SCOPE +from trace_gc.retrieval.service import HybridRetriever, validate_context +from trace_gc.retrieval.store import InMemoryGraphAdapter + + +class PrerequisiteClosureTests(unittest.TestCase): + def setUp(self): + self.f = domain_corpus() + self.c = self.f['catalog'] + self.snapshot = self.c.get(self.f['snapshot_id'], 'graph-snapshot') + self.statuses = deepcopy(self.f['statuses']) + self.sources, self.evidence = {}, {} + # e-support -> e-prereq-1 -> e-prereq-2 (both outside the selected domain) + for ref, subject, obj in (('e-prereq-1', 'Paper-D', 'Method-S1'), ('e-prereq-2', 'Paper-E', 'Method-S2')): + self.snapshot['nodes'].update({subject: 'Document', obj: 'Method'}) + source = self.c.source('source-' + ref, '1', 'Synthetic prerequisite fact ' + ref + '.', scope=SCOPE) + evidence = self.c.evidence(source) + self.sources[ref], self.evidence[ref] = source, evidence + self.statuses[source] = {'active': True, 'permission': 'READ', 'epoch': 1, + 'updated_at': '2026-09-27T00:00:00Z', 'tombstone': False} + self.snapshot['source_epochs'][source] = 1 + self.snapshot['assertions'][ref] = { + 'assertion': {'subject': subject, 'predicate': 'uses_method', 'object': obj, 'qualifiers': {}}, + 'evidence_ids': [evidence], 'prerequisites': [], 'active': True, 'revision': 1} + self.snapshot['assertions']['e-prereq-1']['prerequisites'] = ['e-prereq-2'] + self.snapshot['assertions']['e-support']['prerequisites'] = ['e-prereq-1'] + self.scope = research_domain_scope(self.c, self.f['taxonomy_id'], ['research:biology']) + self.budget = RetrievalBudget(maximum_tokens=150000, maximum_latency_ms=20000, + maximum_edges=100, maximum_nodes=100, maximum_source_spans=100) + self.refresh() + + def refresh(self): + validate_graph(self.snapshot['nodes'], self.snapshot['assertions'], + self.c.get(self.snapshot['schema_id'], 'schema')['relations']) + self.snapshot_id = self.c.put('graph-snapshot', self.snapshot) + self.adapter = InMemoryGraphAdapter(self.c, [self.snapshot_id], self.statuses) + self.retriever = HybridRetriever(self.adapter, catalog=self.c, + access_policy=demo_access(self.c, self.snapshot_id)) + + def request(self, **changes): + return query(requesting_component='prerequisite-closure-regression', security_scope=SCOPE, + text=changes.pop('text', 'improves'), strategies=changes.pop('strategies', ['LEXICAL']), + include_conflicts=False, research_domain_scope=changes.pop('research_domain_scope', self.scope), + budget=changes.pop('budget', self.budget), **changes) + + def retrieve(self, **changes): + result = self.c.get(self.retriever.retrieve(self.request(**changes)), 'retrieval-result') + context = self.c.get(result['graph_context_id'], 'graph-context') + validate_context(self.c, result['graph_context_id'], current_access=self.retriever.access_policy, + current_status=self.adapter.current_source_status()) + return result, context + + def assertNoGraphState(self, context): + # A bare source span may remain an in-domain evidence hit; no graph fact may. + self.assertEqual([i['kind'] for i in context['items'] if i['kind'] != 'EVIDENCE'], []) + self.assertTrue(all(not i['assertion_ids'] for i in context['items'])) + self.assertNotIn('e-support', context['retrieved_edges']) + for ref in ('e-prereq-1', 'e-prereq-2'): + self.assertNotIn(self.evidence[ref], context['selected_evidence_ids']) + + def deny(self, ref): + policy = deepcopy(self.retriever.access_policy) + del policy['grants']['source:' + self.sources[ref]] + self.retriever.set_access_policy(policy) + + def test_complete_prerequisite_chain_travels_with_the_anchor(self): + _, context = self.retrieve() + self.assertEqual(len(context['items']), 1) + item = context['items'][0] + self.assertTrue({'e-support', 'e-prereq-1', 'e-prereq-2'} <= set(item['assertion_ids'])) + for ref in ('e-prereq-1', 'e-prereq-2'): + self.assertIn(self.evidence[ref], item['evidence_ids']) + self.assertIn(self.sources[ref], item['source_ids']) + self.assertIn(ref, item['research_domain']['closure_assertion_ids']) + self.assertIn('e-support', item['research_domain']['anchor_assertion_ids']) + self.assertTrue({'e-prereq-1', 'e-prereq-2'} <= set(context['retrieved_edges'])) + + def test_prerequisite_is_never_an_independent_topical_hit(self): + _, context = self.retrieve(text='Synthetic prerequisite fact e-prereq-2') + self.assertEqual(context['items'], []) + self.assertNotIn('e-prereq-2', context['retrieved_edges']) + + def test_denied_first_level_prerequisite_excludes_the_dependent_without_leakage(self): + self.deny('e-prereq-1') + _, context = self.retrieve() + self.assertNoGraphState(context) + + def test_denied_transitive_prerequisite_excludes_the_dependent_without_leakage(self): + self.deny('e-prereq-2') + _, context = self.retrieve() + self.assertNoGraphState(context) + + def test_revoked_prerequisite_source_invalidates_cached_closure_and_old_context(self): + original, context = self.retrieve() + self.assertIn('e-prereq-2', context['retrieved_edges']) + self.retrieve() + self.assertEqual(self.retriever.cache.hits, 1) + self.adapter.source_status[self.sources['e-prereq-2']].update(active=False, epoch=2) + _, revoked = self.retrieve() + self.assertNoGraphState(revoked) + with self.assertRaises(ContractError): + validate_context(self.c, original['graph_context_id'], current_access=self.retriever.access_policy, + current_status=self.adapter.current_source_status()) + + def test_prerequisite_outside_the_requested_validity_window_excludes_the_dependent(self): + self.snapshot['assertions']['e-prereq-2']['assertion']['qualifiers']['valid_until'] = '2020-01-01T00:00:00Z' + self.refresh() + _, unscoped = self.retrieve() + self.assertIn('e-prereq-2', unscoped['items'][0]['assertion_ids']) + _, context = self.retrieve(temporal_scope={'as_of': None, 'valid_at': '2026-01-01T00:00:00Z', 'before_source': None}) + self.assertNoGraphState(context) + + def test_unrelated_anchor_is_unaffected_by_a_denied_prerequisite(self): + self.deny('e-prereq-2') + _, context = self.retrieve(text='Acme owns Bar') + self.assertIn('e-owns', context['retrieved_edges']) + + def test_budget_rejects_the_entire_anchor_not_the_prerequisite_proof(self): + accepted, context = self.retrieve() + needed = len(context['items'][0]['assertion_ids']) + spans = len(context['items'][0]['evidence_ids']) + self.assertGreaterEqual(needed, 3) + for budget in (replace(self.budget, maximum_edges=needed - 1), + replace(self.budget, maximum_source_spans=spans - 1)): + with self.subTest(budget=budget): + result, rejected = self.retrieve(budget=budget) + self.assertEqual(result['status'], 'PARTIAL') + self.assertEqual(rejected['items'], []) + self.assertEqual(rejected['selected_evidence_ids'], []) + exact, fitted = self.retrieve(budget=replace(self.budget, maximum_edges=needed, maximum_source_spans=spans)) + self.assertEqual(len(fitted['items']), 1) + + def test_budget_sized_for_the_unproven_anchor_alone_is_rejected(self): + _, full = self.retrieve() + full_edges = len(full['items'][0]['assertion_ids']) + bare = deepcopy(self.snapshot) + for ref in ('e-prereq-1', 'e-prereq-2'): + del bare['assertions'][ref] + bare['assertions']['e-support']['prerequisites'] = [] + saved, self.snapshot = self.snapshot, bare + self.refresh() + _, context = self.retrieve() + bare_edges = len(context['items'][0]['assertion_ids']) + self.snapshot = saved + self.refresh() + self.assertEqual(full_edges - bare_edges, 2) + result, rejected = self.retrieve(budget=replace(self.budget, maximum_edges=bare_edges)) + self.assertEqual(result['status'], 'PARTIAL') + self.assertEqual(rejected['items'], []) + + def test_tampering_with_a_required_prerequisite_fails_canonical_validation(self): + _, context = self.retrieve() + context['items'][0]['assertion_ids'].remove('e-prereq-2') + forged = self.c.put('graph-context', context) + with self.assertRaises(ContractError) as caught: + validate_context(self.c, forged, current_access=self.retriever.access_policy, + current_status=self.adapter.current_source_status()) + self.assertEqual(caught.exception.code, 'CONTEXT_MATERIALIZATION') + + def test_literal_pin_also_carries_prerequisites(self): + legacy = deepcopy(self.scope) + legacy['conflict_resolution'] = 'literal-v1' + with patch('trace_gc.retrieval.service.require_live_scope'): + _, context = self.retrieve(research_domain_scope=legacy) + self.assertTrue({'e-support', 'e-prereq-1', 'e-prereq-2'} <= set(context['items'][0]['assertion_ids'])) + self.deny('e-prereq-1') + with patch('trace_gc.retrieval.service.require_live_scope'): + _, denied = self.retrieve(research_domain_scope=legacy) + self.assertNoGraphState(denied) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_research_domain_replay_integrity.py b/tests/test_research_domain_replay_integrity.py new file mode 100644 index 0000000..60199f9 --- /dev/null +++ b/tests/test_research_domain_replay_integrity.py @@ -0,0 +1,120 @@ +"""A retrieval replay of a domain-aware context must state, and keep, its classification pin. + +Synthetic fixtures only. The replay record is produced by `replay_retrieval`; each +negative case edits a copy of that record and re-stores it, so schema-valid forgeries +reach `validate_record`. +""" +from copy import deepcopy +import unittest + +from trace_gc.errors import ContractError +from trace_gc.replay import replay_retrieval +from trace_gc.retrieval.contracts import RetrievalBudget, query +from trace_gc.retrieval.domains import research_domain_scope +from trace_gc.retrieval.fixtures import domain_corpus, SCOPE +from trace_gc.retrieval.integration import validate_record +from trace_gc.retrieval.service import retrieval_fingerprint + +PIN_KEYS = ("original_classification_identity", "replayed_classification_identity", + "original_research_domain_scope", "replayed_research_domain_scope") + + +class ReplayClassificationPinTests(unittest.TestCase): + def setUp(self): + self.f = domain_corpus() + self.c = self.f["catalog"] + self.r = self.f["retriever"] + self.scope = research_domain_scope(self.c, self.f["taxonomy_id"], ["research:biology"]) + budget = RetrievalBudget(maximum_tokens=150000, maximum_latency_ms=20000, + maximum_edges=100, maximum_nodes=100, maximum_source_spans=100) + request = query(requesting_component="replay-integrity", security_scope=SCOPE, text="improves", + strategies=["LEXICAL"], include_conflicts=False, research_domain_scope=self.scope, budget=budget) + self.result_id = self.r.retrieve(request) + self.replay_id = replay_retrieval(self.r, self.result_id, {"retrieval_strategy": ["LEXICAL"]}) + self.replay = self.c.get(self.replay_id, "retrieval-replay") + + def forge(self, mutate): + body = deepcopy(self.replay) + mutate(body) + forged = self.c.put("retrieval-replay", body) + return self.c.record(forged) + + def test_replay_of_a_scoped_context_records_and_validates_its_pins(self): + context = self.c.get(self.c.get(self.result_id, "retrieval-result")["graph_context_id"], "graph-context") + self.assertIn("classification_identity", context) + for key in PIN_KEYS: + self.assertIn(key, self.replay) + self.assertEqual(self.replay["original_research_domain_scope"], self.scope) + self.assertEqual(self.replay["replayed_research_domain_scope"], self.scope) + validate_record(self.c, self.c.record(self.replay_id)) + + def test_a_replay_that_omits_any_pin_is_rejected(self): + for key in PIN_KEYS: + with self.subTest(omitted=key), self.assertRaises(ContractError) as caught: + validate_record(self.c, self.forge(lambda body, key=key: body.pop(key))) + self.assertEqual(caught.exception.code, "DOMAIN_REVISION") + + def test_modern_replay_must_bind_its_disclosure_policy(self): + body = deepcopy(self.replay) + del body["replay_access_id"] + with self.assertRaisesRegex(ContractError, "REPLAY_SCOPE"): + validate_record(self.c, {"kind": "retrieval-replay", "body": body}) + with self.assertRaises(ContractError): + self.c.put("retrieval-replay", body) + + def test_a_replay_with_a_changed_classification_revision_is_rejected(self): + for prefix in ("original", "replayed"): + with self.subTest(side=prefix), self.assertRaises(ContractError) as caught: + validate_record(self.c, self.forge( + lambda body, prefix=prefix: body[prefix + "_classification_identity"].update( + revision=body[prefix + "_classification_identity"]["revision"] + 1))) + self.assertEqual(caught.exception.code, "DOMAIN_REVISION") + + def test_a_replay_with_a_changed_scope_is_rejected(self): + other = research_domain_scope(self.c, self.f["taxonomy_id"], ["research:chemistry"]) + for prefix in ("original", "replayed"): + with self.subTest(side=prefix), self.assertRaises(ContractError) as caught: + validate_record(self.c, self.forge( + lambda body, prefix=prefix: body.__setitem__(prefix + "_research_domain_scope", other))) + self.assertEqual(caught.exception.code, "DOMAIN_REVISION") + + def test_replay_graph_version_matches_the_referenced_context(self): + for prefix in ("original", "replayed"): + key = prefix + "_graph_version" + with self.subTest(side=prefix), self.assertRaises(ContractError) as caught: + validate_record(self.c, self.forge(lambda body: body.update({key: body[key] + 1}))) + self.assertEqual(caught.exception.code, "RETRIEVAL_LINEAGE") + + def test_declared_scope_change_matches_the_replayed_request(self): + other = research_domain_scope(self.c, self.f["taxonomy_id"], ["research:chemistry"]) + with self.assertRaises(ContractError) as caught: + validate_record(self.c, self.forge( + lambda body: body["changed_parameters"].update(research_domain_scope=other))) + self.assertEqual(caught.exception.code, "REPLAY_SCOPE") + + def test_pre_scope_context_still_validates_and_replays_after_classification_migration(self): + original = self.c.get(self.result_id, "retrieval-result") + request = self.c.get(original["query_id"], "retrieval-query") + request.pop("research_domain_scope") + unscoped = self.c.get(self.r.retrieve(request), "retrieval-result") + context = self.c.get(unscoped["graph_context_id"], "graph-context") + lineage = self.c.get(unscoped["lineage_id"], "retrieval-lineage") + for artifact in (context, lineage): + artifact.pop("classification_identity") + artifact.pop("research_domain_scope") + context["retrieval_fingerprint"] = retrieval_fingerprint( + request, context["strategy_versions"], context["embedding_version"], + context["adapter_version"], self.r.access_policy["version"]) + context_id = self.c.put("graph-context", context) + lineage_id = self.c.put("retrieval-lineage", {**lineage, "graph_context_id": context_id}) + legacy_result_id = self.c.put("retrieval-result", { + **unscoped, "graph_context_id": context_id, "lineage_id": lineage_id, + }) + validate_record(self.c, self.c.record(context_id)) + legacy_replay = replay_retrieval(self.r, legacy_result_id, {}) + validate_record(self.c, self.c.record(legacy_replay)) + self.assertEqual(self.c.get(legacy_replay)["original_classification_identity"]["revision"], 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_research_domain_retrieval.py b/tests/test_research_domain_retrieval.py new file mode 100644 index 0000000..3c17d0f --- /dev/null +++ b/tests/test_research_domain_retrieval.py @@ -0,0 +1,693 @@ +"""All-channel reference conformance; every label and response is synthetic. + +The tests require the requested channel's own positive result. Conflict fallback +cannot make an otherwise empty channel appear covered. No live model or authority +is enrolled, and no representative-corpus or deployment claim is made. +""" +from __future__ import annotations + +from base64 import b64decode +from copy import deepcopy +from dataclasses import replace +import unittest +from unittest.mock import patch + +from trace_gc.adapter import record_response +from trace_gc.canonical import digest +from trace_gc.catalog import Catalog +from trace_gc.compiler import compile_pack, validate_pack, wire_request +from trace_gc.demo import fixture_response +from trace_gc.domains import create_assignment, reference_taxonomy +from trace_gc.errors import ContractError +from trace_gc.programs import question +from trace_gc.replay import replay_retrieval +from trace_gc.retrieval.contracts import query, RetrievalBudget, STRATEGIES +from trace_gc.retrieval.domains import ResearchDomainSelection, research_domain_scope +from trace_gc.retrieval.fixtures import domain_corpus, demo_access, SCOPE +from trace_gc.retrieval.integration import validate_record, validate_pack_lineage +from trace_gc.retrieval.items import authorized_scope_edges, canonical_item, conflict_pairs, query_conflicts +from trace_gc.retrieval.planner import RetrievalPlanner +from trace_gc.retrieval.security import AccessFilter +from trace_gc.retrieval.service import GraphRAGQueryService, HybridRetriever, _validate_context_items, validate_context +from trace_gc.retrieval.store import GraphReadView, InMemoryGraphAdapter + + +class SpyEmbedding: + version = "domain-embedding-spy-fixture-v1" + + def __init__(self, callback=None): + self.seen = [] + self.callback = callback + + def embed(self, texts): + self.seen.extend(texts) + if self.callback: + self.callback() + return [[1.0, 0.0] for _ in texts] + + +class DomainRetrievalTests(unittest.TestCase): + def setUp(self): + self.f = domain_corpus() + self.c = self.f["catalog"] + self.r = self.f["retriever"] + self.scope = research_domain_scope(self.c, self.f["taxonomy_id"], ["research:biology"]) + self.budget = RetrievalBudget(maximum_tokens=150000, maximum_latency_ms=20000, + maximum_edges=100, maximum_nodes=100, maximum_source_spans=100) + + def request(self, strategies=None, **changes): + return query(requesting_component="downstream-search", security_scope=SCOPE, + strategies=strategies or ["RELATION"], budget=changes.pop("budget", self.budget), + focus_entities=changes.pop("focus_entities", []), text=changes.pop("text", ""), + include_conflicts=changes.pop("include_conflicts", False), + research_domain_scope=changes.pop("research_domain_scope", self.scope), **changes) + + def context(self, request): + result_id = self.r.retrieve(request) + result = self.c.get(result_id, "retrieval-result") + context = self.c.get(result["graph_context_id"], "graph-context") + validate_context(self.c, result["graph_context_id"], current_access=self.r.access_policy, + current_status=self.f["adapter"].source_status) + validate_record(self.c, self.c.record(result["lineage_id"])) + validate_record(self.c, self.c.record(result_id)) + return context, result + + def add_decisions(self): + """Exercise real compiler/adapter observation records, not invented bodies.""" + result = {} + for edge in ("e-support", "e-refute"): + fact = self.c.get(self.f["snapshot_id"])["assertions"][edge] + candidate = self.c.candidate(id_="candidate:domain-" + edge, run_id="domain-retrieval-fixture", + assertion=fact["assertion"], claim_id=self.f["claim_id"], evidence_ids=fact["evidence_ids"]) + pack = compile_pack(self.c, id_="pack:domain-" + edge, run_id="domain-retrieval-fixture", + candidate_ids=[candidate], questions=[question(candidate, id_="q-" + edge)], + snapshot_id=self.f["snapshot_id"], security_scope=SCOPE) + observation = record_response(self.c, pack, fixture_response(self.c.get(pack)))[0] + result[edge] = (candidate, observation) + self.r.set_access_policy(demo_access(self.c, self.f["snapshot_id"])) + return result + + def test_each_strategy_has_its_own_positive_canonical_result(self): + decisions = self.add_decisions() + self.r.embedding = SpyEmbedding() + cases = { + "ENTITY": ("NODE", {"focus_entities": ["Acme"]}), + "LEXICAL": ("EVIDENCE", {"text": "randomized"}), + "VECTOR": ("EVIDENCE", {"text": "biological methods"}), + "NEIGHBORHOOD": ("EDGE", {"focus_entities": ["Acme"]}), + "PATH": ("PATH", {"focus_entities": ["Acme"], "hop_limit": 2}), + "COMMUNITY": ("COMMUNITY", {"focus_entities": ["Acme"]}), + "GLOBAL": ("EDGE", {}), + "ONTOLOGY": ("ONTOLOGY", {"ontology_scope": ["Organization"], "focus_relationships": ["owns"]}), + "SCHEMA": ("SCHEMA", {"ontology_scope": ["Organization"], "focus_relationships": ["owns"]}), + "RELATION": ("EDGE", {"focus_entities": ["Acme"]}), + "PROVENANCE": ("PROVENANCE", {"focus_entities": ["Acme"]}), + "EVIDENCE": ("EVIDENCE", {"focus_entities": ["Paper-A"]}), + "CONFLICT": ("CONFLICT", {"focus_entities": [self.f["claim_id"]]}), + "DECISION": ("DECISION", {"decision_id": decisions["e-support"][1]}), + "TEMPORAL": ("EDGE", {"focus_entities": ["Acme"], "temporal_scope": { + "as_of": None, "valid_at": "2024-04-02T00:00:00Z", "before_source": None}}), + "SOURCE": ("EVIDENCE", {"source_scope": [self.f["sources"]["e-method"]]}), + "SIMILAR_CASE": ("DECISION", {"text": "Paper-A"}), + "CLAIM": ("CLAIM", {"focus_entities": [self.f["claim_id"]]}), + } + self.assertEqual(set(cases), set(STRATEGIES)) + for strategy, (kind, changes) in cases.items(): + with self.subTest(strategy=strategy): + ctx, result = self.context(self.request([strategy], **changes)) + own = [item for item in ctx["items"] if item["kind"] == kind] + self.assertTrue(own, (strategy, ctx["items"], result["warnings"])) + lineage = self.c.get(result["lineage_id"]) + selected_ids = {item["id"] for item in own} + self.assertTrue(any(row["item_id"] in selected_ids and strategy in row["methods"] + for row in lineage["candidates"])) + self.assertTrue(all(not item["instruction_authority"] for item in ctx["items"])) + self.assertEqual(ctx["research_domain_scope"], self.scope) + + def test_every_strategy_excludes_unrelated_domain_even_with_positive_text(self): + decisions = self.add_decisions() + self.r.embedding = SpyEmbedding() + absent = research_domain_scope(self.c, self.f["taxonomy_id"], ["research:mathematics"]) + for strategy in STRATEGIES: + with self.subTest(strategy=strategy): + ctx, _ = self.context(self.request([strategy], text="Paper-A Acme randomized Intervention", + focus_entities=["Acme", "Paper-A", self.f["claim_id"]], focus_relationships=["owns"], + ontology_scope=["Organization"], decision_id=decisions["e-support"][1], + include_historical=True, research_domain_scope=absent, hop_limit=2)) + self.assertEqual(ctx["items"], []) + self.assertEqual(self.r.embedding.seen, []) + + def test_cross_domain_refutation_is_atomic_with_lexical_anchor(self): + ctx, _ = self.context(self.request(["LEXICAL"], text="improves")) + self.assertEqual(len(ctx["items"]), 1) + item = ctx["items"][0] + self.assertEqual(item["canonical_ref"], self.f["evidence"]["e-support"]) + self.assertEqual(set(item["assertion_ids"]), {"e-support", "e-refute"}) + self.assertEqual(item["trust_class"], "CONFLICTED_GRAPH_FACT") + self.assertEqual(set(item["evidence_ids"]), {self.f["evidence"]["e-support"], self.f["evidence"]["e-refute"]}) + self.assertEqual(item["research_domain"]["anchor_assertion_ids"], ["e-support"]) + self.assertIn("e-refute", item["research_domain"]["closure_assertion_ids"]) + self.assertIn("did not improve", self.c.get(self.f["evidence"]["e-refute"])["quote"]) + + def test_anchor_relation_source_filters_do_not_hide_required_refutation(self): + for filters in ({"allowed_relation_types": ["supports"]}, {"excluded_relation_types": ["refutes"]}, + {"source_scope": [self.f["sources"]["e-support"]]}, + {"allowed_relation_types": ["supports"], "source_scope": [self.f["sources"]["e-support"]]}): + with self.subTest(filters=filters): + ctx, _ = self.context(self.request(["LEXICAL"], text="improves", **filters)) + self.assertEqual(set(ctx["retrieved_edges"]), {"e-support", "e-refute"}) + + def test_refutation_outside_domain_is_not_an_independent_vector_input(self): + spy = SpyEmbedding() + self.r.embedding = spy + ctx, _ = self.context(self.request(["VECTOR"], text="Intervention")) + for edge in ("e-refute", "e-dataset", "e-partner", "e-replicate"): + self.assertNotIn(self.c.get(self.f["evidence"][edge])["quote"], spy.seen) + self.assertIn(self.c.get(self.f["evidence"]["e-support"])["quote"], spy.seen) + self.assertIn("e-refute", ctx["retrieved_edges"]) + + def test_refutation_is_not_an_independent_lexical_candidate(self): + ctx, _ = self.context(self.request(["LEXICAL"], text="did not")) + self.assertEqual(ctx["items"], []) + + def test_multi_domain_any_and_all(self): + both = research_domain_scope(self.c, self.f["taxonomy_id"], ["research:biology", "research:chemistry"], match="ALL") + ctx, _ = self.context(self.request(["LEXICAL"], text="owns improves randomized", research_domain_scope=both)) + anchors = {item["canonical_ref"] for item in ctx["items"]} + self.assertEqual(anchors, {self.f["evidence"]["e-path"], self.f["evidence"]["e-support"]}) + any_scope = {**both, "match": "ANY"} + ctx, _ = self.context(self.request(["LEXICAL"], text="owns improves randomized", research_domain_scope=any_scope)) + self.assertTrue({self.f["evidence"]["e-owns"], self.f["evidence"]["e-method"]} <= + {item["canonical_ref"] for item in ctx["items"]}) + + def test_unclassified_is_explicit_not_a_domain_id(self): + ctx, _ = self.context(self.request(["LEXICAL"], text="replicates")) + self.assertEqual(ctx["items"], []) + unknown = research_domain_scope(self.c, self.f["taxonomy_id"], [], include_unclassified=True) + ctx, _ = self.context(self.request(["LEXICAL"], text="replicates", research_domain_scope=unknown)) + self.assertEqual([item["canonical_ref"] for item in ctx["items"]], [self.f["evidence"]["e-replicate"]]) + self.assertEqual(ctx["items"][0]["research_domain"]["source_assignments"], {self.f["sources"]["e-replicate"]: None}) + + def test_unclassified_refutation_is_still_required_explanatory_evidence(self): + snap = self.c.get(self.f["snapshot_id"]) + del snap["classifications"]["assignments"][self.f["sources"]["e-refute"]] + self.replace_snapshot(snap) + ctx, _ = self.context(self.request(["LEXICAL"], text="improves")) + self.assertIn("e-refute", ctx["retrieved_edges"]) + self.assertIsNone(ctx["items"][0]["research_domain"]["source_assignments"][self.f["sources"]["e-refute"]]) + + def test_assertion_membership_comes_from_evidence_not_entity_name(self): + ctx, _ = self.context(self.request(["RELATION"], focus_entities=["Acme"])) + anchors = {item["canonical_ref"] for item in ctx["items"]} + self.assertIn("e-owns", anchors) + self.assertNotIn("e-partner", anchors) + self.assertNotIn("e-new", anchors) + self.assertIn("e-alias", ctx["retrieved_edges"]) + + def test_alias_node_uses_authorized_cross_domain_identity_proof(self): + ctx, _ = self.context(self.request(["ENTITY"], focus_entities=["Acme-Holdings"])) + self.assertEqual(len(ctx["items"]), 1) + self.assertEqual(ctx["items"][0]["canonical_ref"], "Acme-Holdings") + self.assertTrue({"e-alias", "e-owns"} <= set(ctx["retrieved_edges"])) + policy = deepcopy(self.r.access_policy) + del policy["grants"]["source:" + self.f["sources"]["e-alias"]] + self.r.set_access_policy(policy) + ctx, _ = self.context(self.request(["ENTITY"], focus_entities=["Acme-Holdings"])) + self.assertEqual(ctx["items"], []) + + def test_path_members_remain_search_hops_not_identity_closure(self): + ctx, result = self.context(self.request(["PATH"], focus_entities=["Acme"], hop_limit=2)) + self.assertTrue(all("e-alias" not in item["member_assertion_ids"] for item in ctx["items"])) + item = next(item for item in ctx["items"] if set(item["member_assertion_ids"]) == {"e-owns", "e-path"}) + self.assertEqual(len(item["member_assertion_ids"]), 2) + self.assertIn("e-alias", item["assertion_ids"]) + self.assertNotIn("e-alias", item["member_assertion_ids"]) + self.assertEqual(item["research_domain"]["anchor_assertion_ids"], ["e-owns", "e-path"]) + self.assertEqual(item["research_domain"]["closure_assertion_ids"], ["e-alias"]) + alias_source = self.f["sources"]["e-alias"] + self.assertEqual(item["research_domain"]["source_assignments"][alias_source], self.f["assignments"][alias_source]) + self.assertIn("not additional search-path hops", item["text"]) + lineage = self.c.get(result["lineage_id"], "retrieval-lineage") + candidate = next(row for row in lineage["candidates"] if row["item_id"] == item["id"]) + self.assertEqual(candidate["features"]["graph_distance_utility"], 0.5) + + def test_out_of_domain_focus_does_not_expand_to_unfocused_search(self): + for strategy in ("RELATION", "TEMPORAL", "PROVENANCE", "COMMUNITY", "CONFLICT"): + with self.subTest(strategy=strategy): + context, _ = self.context(self.request([strategy], focus_entities=["Paper-B"])) + self.assertEqual(context["items"], []) + + def test_all_path_members_contribute_labels_across_the_path(self): + scope = research_domain_scope(self.c, self.f["taxonomy_id"], + ["research:biology", "research:chemistry"], match="ALL") + source = self.f["sources"]["e-path"] + snapshot = self.c.get(self.f["snapshot_id"]) + previous = snapshot["classifications"]["assignments"][source] + assignment = self.c.get(previous) + snapshot["classifications"]["assignments"][source] = create_assignment( + self.c, source_snapshot_id=source, taxonomy_id=self.f["taxonomy_id"], + domain_ids=["research:chemistry"], review=assignment["review"], + classifier_id="synthetic-topology", classifier_version="fixture-v1", supersedes=previous) + snapshot["classifications"]["revision"] += 1 + self.replace_snapshot(snapshot) + ctx, _ = self.context(self.request(["PATH"], focus_entities=["Acme"], hop_limit=2, research_domain_scope=scope)) + self.assertEqual([item["research_domain"]["anchor_assertion_ids"] for item in ctx["items"]], + [["e-owns", "e-path"]]) + + def test_community_scope_remains_topology_not_taxonomy(self): + ctx, _ = self.context(self.request(["COMMUNITY"], focus_entities=["Acme"])) + item = next(item for item in ctx["items"] if item["kind"] == "COMMUNITY") + ctx2, _ = self.context(self.request(["COMMUNITY"], focus_entities=["Acme"], community_scope=[item["canonical_ref"]])) + self.assertTrue(ctx2["items"]) + other_scope = self.request(["COMMUNITY"], focus_entities=["Acme"], community_scope=["research:biology"]) + ctx3, _ = self.context(other_scope) + self.assertEqual(ctx3["items"], []) + view = self.r.adapter.read(other_scope) + access = AccessFilter(self.r.access_policy, view.catalog, view.source_status) + with self.assertRaisesRegex(ContractError, "COMMUNITY_SCOPE"): + canonical_item(view, access, other_scope, kind="COMMUNITY", ref=item["canonical_ref"], + members=item["member_assertion_ids"]) + self.assertTrue(item["generated_summary"]) + self.assertFalse(item["instruction_authority"]) + self.assertEqual(item["member_assertion_ids"], ["e-owns", "e-path"]) + self.assertEqual(item["research_domain"]["closure_assertion_ids"], ["e-alias"]) + self.assertIn(self.f["evidence"]["e-alias"], item["evidence_ids"]) + + def test_conflict_pair_keeps_refutation_as_closure_without_standalone_anchor(self): + ctx, _ = self.context(self.request(["CONFLICT", "PROVENANCE", "RELATION"], + focus_entities=[self.f["claim_id"]])) + item = next(item for item in ctx["items"] if item["kind"] == "CONFLICT") + self.assertEqual(set(item["member_assertion_ids"]), {"e-support", "e-refute"}) + self.assertEqual(item["research_domain"]["anchor_assertion_ids"], ["e-support"]) + self.assertEqual(item["research_domain"]["closure_assertion_ids"], ["e-refute"]) + self.assertIn(self.f["evidence"]["e-refute"], item["evidence_ids"]) + self.assertFalse(any(item["canonical_ref"] == "e-refute" for item in ctx["items"])) + + def test_schema_requires_acl_and_authorized_topical_basis(self): + ctx, _ = self.context(self.request(["SCHEMA"], focus_relationships=["uses_dataset"])) + # A schema rule may be relevant to an authorized selected endpoint type + # even when its only existing instance is outside the topical anchors. + self.assertTrue(ctx["schema_fragments"]) + self.assertNotIn("e-dataset", ctx["retrieved_edges"]) + ctx, _ = self.context(self.request(["SCHEMA"], focus_relationships=["owns"], ontology_scope=["Organization"])) + self.assertTrue(ctx["schema_fragments"]) + policy = deepcopy(self.r.access_policy) + del policy["grants"]["schema:" + self.f["schema_id"]] + self.r.set_access_policy(policy) + ctx, _ = self.context(self.request(["SCHEMA", "ONTOLOGY"], focus_relationships=["owns"], ontology_scope=["Organization"])) + self.assertEqual(ctx["items"], []) + + def test_decision_and_hypothesis_require_own_authorized_membership(self): + decisions = self.add_decisions() + for strategy in ("DECISION", "SIMILAR_CASE"): + with self.subTest(strategy=strategy): + ctx, _ = self.context(self.request([strategy], text="Intervention Paper", focus_entities=[self.f["claim_id"]], + include_historical=True)) + refs = {item["canonical_ref"] for item in ctx["items"]} + self.assertTrue(set(decisions["e-support"]) <= refs) + self.assertFalse(set(decisions["e-refute"]) & refs) + self.assertIn("e-refute", ctx["retrieved_edges"]) + policy = deepcopy(self.r.access_policy) + for record in decisions["e-support"]: + del policy["grants"]["decision:" + record] + self.r.set_access_policy(policy) + ctx, _ = self.context(self.request(["DECISION"], focus_entities=[self.f["claim_id"]], include_historical=True)) + self.assertEqual(ctx["items"], []) + + def test_no_self_candidate_or_inflight_vote_as_corroboration(self): + decisions = self.add_decisions() + candidate, observation = decisions["e-support"] + request = self.request(["DECISION", "SIMILAR_CASE"], text="Intervention Paper", + focus_entities=[self.f["claim_id"]], candidate_id=candidate, include_historical=True) + ctx, _ = self.context(request) + self.assertFalse(set(decisions["e-support"]) & {item["canonical_ref"] for item in ctx["items"]}) + view = self.r.adapter.read(request) + access = AccessFilter(self.r.access_policy, view.catalog, view.source_status) + for kind, ref in (("DECISION", observation), ("DECISION", candidate), ("HYPOTHESIS", candidate)): + with self.subTest(kind=kind, ref=ref), self.assertRaisesRegex(ContractError, "RESEARCH_DOMAIN_SCOPE"): + canonical_item(view, access, request, kind=kind, ref=ref) + + def test_domain_match_never_overrides_source_acl_before_embedding(self): + denied = self.f["sources"]["e-method"] + policy = deepcopy(self.r.access_policy) + del policy["grants"]["source:" + denied] + self.r.set_access_policy(policy) + spy = SpyEmbedding() + self.r.embedding = spy + original = GraphReadView.source_classification + examined = [] + def guarded(view, source_id, access): + result = original(view, source_id, access) + if source_id == denied: + examined.append(result) + return result + with patch.object(GraphReadView, "source_classification", guarded): + ctx, _ = self.context(self.request(["VECTOR"], text="randomized")) + self.assertTrue(examined) + self.assertTrue(all(row is None for row in examined)) + self.assertNotIn(self.c.get(denied)["text"], spy.seen) + self.assertNotIn(self.f["evidence"]["e-method"], ctx["selected_evidence_ids"]) + + def test_current_status_blocks_embedding_in_historical_mode(self): + for status in ({"active": False}, {"permission": "DENIED"}, {"tombstone": True, "active": False, "permission": "DENIED"}): + with self.subTest(status=status): + source = self.f["sources"]["e-method"] + self.f["adapter"].source_status[source].update(status) + spy = SpyEmbedding() + self.r.embedding = spy + ctx, _ = self.context(self.request(["VECTOR"], text="randomized", include_historical=True, mode="HISTORICAL")) + self.assertNotIn(self.c.get(source)["text"], spy.seen) + self.assertNotIn(self.f["evidence"]["e-method"], ctx["selected_evidence_ids"]) + self.f["adapter"].source_status[source].update(active=True, permission="READ", tombstone=False) + + def test_denied_cross_domain_refutation_does_not_leak_through_closure(self): + policy = deepcopy(self.r.access_policy) + del policy["grants"]["source:" + self.f["sources"]["e-refute"]] + self.r.set_access_policy(policy) + ctx, _ = self.context(self.request(["LEXICAL"], text="improves")) + self.assertEqual(ctx["retrieved_edges"], ["e-support"]) + self.assertNotIn(self.f["evidence"]["e-refute"], ctx["selected_evidence_ids"]) + self.assertNotIn(self.f["sources"]["e-refute"], ctx["items"][0]["research_domain"]["source_assignments"]) + + def test_revocation_during_embedding_fails_before_context_publication(self): + source = self.f["sources"]["e-method"] + before = len(self.c.all("graph-context")) + counted_sources = set() + + def revoke(): + self.f["adapter"].source_status[source].update(active=False, epoch=2) + + def count(item): + counted_sources.update(item["source_ids"]) + return 0 + + self.r.embedding = SpyEmbedding(revoke) + self.r.token_counter = count + with self.assertRaisesRegex(ContractError, "ACCESS_DENIED"): + self.r.retrieve(self.request(["VECTOR"], text="randomized")) + self.assertEqual(len(self.c.all("graph-context")), before) + self.assertNotIn(source, counted_sources) + # It was allowed at entry to this synchronous call; no cancellation of + # an already delivered model request or production SLO is asserted. + + def test_scoped_selection_requires_a_current_status_view(self): + source = self.f["sources"]["e-method"] + adapter = self.f["adapter"] + read = adapter.read + + def read_then_withdraw(request): + view = read(request) + adapter.source_status[source].update(active=False, epoch=2) + return view + + spy = SpyEmbedding() + self.r.embedding = spy + with patch.object(adapter, "read", read_then_withdraw), self.assertRaisesRegex(ContractError, "STALE_SOURCE_EPOCH"): + self.r.retrieve(self.request(["VECTOR"], text="randomized")) + self.assertEqual(spy.seen, []) + + def test_source_epoch_change_during_embedding_requires_fresh_read(self): + source = self.f["sources"]["e-method"] + self.r.embedding = SpyEmbedding(lambda: self.f["adapter"].source_status[source].update(epoch=2)) + with self.assertRaisesRegex(ContractError, "STALE_SOURCE_EPOCH"): + self.r.retrieve(self.request(["VECTOR"], text="randomized")) + + def test_withdrawal_invalidates_retrieval_cache(self): + q = self.request(["LEXICAL"], text="randomized") + _, first = self.context(q) + _, second = self.context(q) + self.assertFalse(self.c.get(first["lineage_id"])["cache_hit"]) + self.assertTrue(self.c.get(second["lineage_id"])["cache_hit"]) + self.f["adapter"].source_status[self.f["sources"]["e-method"]].update(active=False, epoch=2) + ctx, third = self.context(q) + self.assertFalse(self.c.get(third["lineage_id"])["cache_hit"]) + self.assertEqual(ctx["items"], []) + + def test_tampered_cached_domain_proof_is_reconstructed_and_rejected(self): + q = self.request(["LEXICAL"], text="improves") + self.context(q) + rows = next(iter(self.r.cache._entries.values())) + rows[0]["item"]["research_domain"]["classification_hash"] = "0" * 64 + with self.assertRaisesRegex(ContractError, "CONTEXT_MATERIALIZATION"): + self.r.retrieve(q) + + def test_budget_never_keeps_support_without_required_refutation(self): + for budget in (replace(self.budget, maximum_edges=1), replace(self.budget, maximum_source_spans=1), + replace(self.budget, maximum_tokens=1)): + with self.subTest(budget=budget): + ctx, result = self.context(self.request(["LEXICAL"], text="improves", budget=budget)) + self.assertEqual(ctx["items"], []) + self.assertEqual(result["status"], "PARTIAL") + self.assertEqual(ctx["selected_evidence_ids"], []) + + def test_plugin_cannot_inject_out_of_domain_lexical_candidate(self): + target = self.f["evidence"]["e-dataset"] + class Malicious: + version = "malicious-domain-fixture-v1" + def retrieve(plugin, space): + # Even an individually ACL-authorized raw legacy candidate must + # pass canonical domain admission at the shared service boundary. + old_query = {**space.query, "research_domain_scope": None} + yield canonical_item(space.view, space.access, old_query, kind="EVIDENCE", ref=target) + self.r.strategies["LEXICAL"] = Malicious() + with self.assertRaisesRegex(ContractError, "RESEARCH_DOMAIN_SCOPE"): + self.r.retrieve(self.request(["LEXICAL"], text="Dataset")) + + def test_context_scope_and_revision_forgery_fail_closed(self): + ctx, _ = self.context(self.request(["LEXICAL"], text="improves")) + for update in ({"classification_identity": {**ctx["classification_identity"], "revision": 999}}, + {"research_domain_scope": {**self.scope, "domain_ids": ["research:physics"]}}): + with self.subTest(update=update): + forged = self.c.put("graph-context", {**ctx, **update}) + with self.assertRaisesRegex(ContractError, "DOMAIN_REVISION"): + validate_context(self.c, forged) + + def test_stripped_cross_domain_refutation_fails_canonical_validation(self): + ctx, _ = self.context(self.request(["LEXICAL"], text="improves")) + ctx["items"][0]["assertion_ids"].remove("e-refute") + forged = self.c.put("graph-context", ctx) + with self.assertRaisesRegex(ContractError, "CONTEXT_MATERIALIZATION"): + validate_context(self.c, forged) + + def test_scope_rejects_unknown_taxonomy_hash_and_domain(self): + for fields in ({"taxonomy_hash": "0" * 64}, {"domain_ids": ["research:invented"]}, + {"domain_ids": []}, {"domain_ids": ["research:physics", "research:biology"]}): + with self.subTest(fields=fields), self.assertRaises(ContractError): + self.r.retrieve(self.request(research_domain_scope={**self.scope, **fields})) + + def test_packaged_taxonomy_proposal_cannot_be_used_as_reviewed_scope(self): + proposal = self.c.add(reference_taxonomy()) + # Catalog.add does not return an ID; use the immutable envelope ID. + proposal_id = reference_taxonomy()["id"] + with self.assertRaisesRegex(ContractError, "RESEARCH_DOMAIN_SCOPE"): + research_domain_scope(self.c, proposal_id, ["research:biology"]) + + def test_classification_does_not_grant_unknown_nodes_a_domain(self): + snap = self.c.get(self.f["snapshot_id"]) + snap["nodes"]["research:biology"] = "Type" + self.replace_snapshot(snap) + policy = demo_access(self.c, self.f["snapshot_id"]) + self.r.set_access_policy(policy) + ctx, _ = self.context(self.request(["ENTITY"], focus_entities=["research:biology"], text="research biology")) + self.assertEqual(ctx["items"], []) + + def test_scope_is_preserved_in_downstream_answer_and_lineage(self): + answer_id = GraphRAGQueryService(self.r).query(self.request(["LEXICAL"], text="improves"))["answer_context_id"] + answer = self.c.get(answer_id, "graphrag-answer") + validate_record(self.c, self.c.record(answer_id)) + context = self.c.get(answer["graph_context_id"]) + self.assertEqual(answer["research_domain_scope"], self.scope) + self.assertEqual(answer["classification_identity"], context["classification_identity"]) + self.assertEqual({row["evidence_id"] for row in answer["citations"]}, {self.f["evidence"]["e-support"], self.f["evidence"]["e-refute"]}) + + def test_planner_carries_scope_and_rejects_override(self): + planner = RetrievalPlanner() + plan_id = planner.plan(self.c, candidate_id=None, question_type="ASSERTION", risk_class="R1", + known_entities=["Acme"], known_relations=["owns"], budget=self.budget, research_domain_scope=self.scope) + plan = self.c.get(plan_id) + self.assertEqual(plan["research_domain_scope"], self.scope) + q = planner.request(self.c, plan_id, security_scope=SCOPE, text="Acme", retrieval_round=0) + self.assertEqual(q["research_domain_scope"], self.scope) + other = {**self.scope, "domain_ids": ["research:physics"]} + with self.assertRaisesRegex(ContractError, "RETRIEVAL_PLAN_BINDING"): + self.r.retrieve({**q, "research_domain_scope": other}, plan_id=plan_id) + + def test_upstream_minimum_closure_and_replay_pin_the_same_domain_revision(self): + fact = self.c.get(self.f["snapshot_id"])["assertions"]["e-support"] + candidate = self.c.candidate(id_="candidate:new-domain", run_id="upstream-domain-test", assertion=fact["assertion"], + claim_id=self.f["claim_id"], evidence_ids=fact["evidence_ids"]) + request = self.request(["LEXICAL"], text="improves", candidate_id=candidate) + request["requesting_component"] = "upstream-synthesis" + ctx, result = self.context(request) + pack_id = compile_pack(self.c, id_="pack:new-domain", run_id="upstream-domain-test", candidate_ids=[candidate], + questions=[question(candidate, id_="new-support")], snapshot_id=self.f["snapshot_id"], security_scope=SCOPE, + graph_context_ids=[result["graph_context_id"]], source_retrieval_ids=[], request_cap=1000000, state_longest_cap=1000000) + pack = self.c.get(pack_id) + validate_pack(self.c, pack, source_status=self.f["adapter"].source_status, current_graph_access=self.r.access_policy) + validate_pack_lineage(self.c, pack, current_status=self.f["adapter"].source_status, current_access=self.r.access_policy) + self.assertTrue({self.f["evidence"]["e-support"], self.f["evidence"]["e-refute"]} <= set(pack["closure"]["evidence_ids"])) + graph = pack["state"]["graph_context"][0] + self.assertEqual(graph["classification_identity"], ctx["classification_identity"]) + self.assertEqual(graph["research_domain_scope"], self.scope) + for field in ("classification_identity", "research_domain_scope"): + ref = result["graph_context_id"] + self.assertIn({"path": f"/graph_context/0/{field}", "record_id": ref, + "record_hash": self.c.hash(ref), "locator": f"/{field}", + "transformation": "identity-v1"}, pack["materialization"]) + replay_id = replay_retrieval(self.r, self.c.put("retrieval-result", result), {"retrieval_strategy": ["RELATION"]}) + replay = self.c.get(replay_id) + validate_record(self.c, self.c.record(replay_id)) + self.assertEqual(replay["original_classification_identity"], replay["replayed_classification_identity"]) + self.assertEqual(replay["replayed_research_domain_scope"], self.scope) + + def test_unscoped_model_wire_retains_the_existing_graph_context_shape(self): + fact = self.c.get(self.f["snapshot_id"])["assertions"]["e-support"] + candidate = self.c.candidate(id_="candidate:unscoped-pack", run_id="unscoped-pack", + assertion=fact["assertion"], claim_id=self.f["claim_id"], + evidence_ids=fact["evidence_ids"]) + request = self.request(["LEXICAL"], text="improves", candidate_id=candidate, research_domain_scope=None) + request["requesting_component"] = "upstream-synthesis" + ctx, result = self.context(request) + ref = result["graph_context_id"] + pack_id = compile_pack(self.c, id_="pack:unscoped", run_id="unscoped-pack", candidate_ids=[candidate], + questions=[question(candidate, id_="support")], snapshot_id=self.f["snapshot_id"], + security_scope=SCOPE, graph_context_ids=[ref], source_retrieval_ids=[]) + pack = self.c.get(pack_id) + expected = deepcopy(pack) + expected["state"]["graph_context"] = [{"context_id": ref, "items": ctx["items"], + "instruction_authority": False}] + self.assertEqual(b64decode(pack["request_base64"]), wire_request(expected)) + self.assertFalse(any(row["path"].startswith("/graph_context/0/") and row["locator"] != "/items" + for row in pack["materialization"])) + + def test_old_context_revalidation_respects_now_revoked_source(self): + _, result = self.context(self.request(["LEXICAL"], text="improves")) + self.f["adapter"].source_status[self.f["sources"]["e-refute"]].update(active=False, epoch=2) + with self.assertRaises(ContractError): + self.r.validate_live_context(result["graph_context_id"]) + + def test_scoped_unmigrated_adapter_needs_current_status_capability(self): + snap = self.c.get(self.f["snapshot_id"]) + del snap["classifications"] + self.replace_snapshot(snap) + adapter = self.f["adapter"] + class NoCurrentStatus: + version = "no-current-status-fixture-v1" + def read(self, q): + return adapter.read(q) + self.r.adapter = NoCurrentStatus() + unknown = research_domain_scope(self.c, self.f["taxonomy_id"], [], include_unclassified=True) + with self.assertRaisesRegex(ContractError, "SOURCE_STATUS_CAPABILITY"): + self.r.retrieve(self.request(["LEXICAL"], text="randomized", research_domain_scope=unknown)) + + def test_unscoped_migrated_read_supports_original_adapter_protocol(self): + adapter = self.f["adapter"] + + class ReadOnlyAdapter: + version = "legacy-read-only-fixture-v1" + + def read(self, request): + return adapter.read(request) + + self.r.adapter = ReadOnlyAdapter() + context, result = self.context(self.request(["LEXICAL"], text="randomized", research_domain_scope=None)) + self.assertTrue(context["classification_identity"]["migrated"]) + self.assertTrue(context["items"]) + self.r.validate_live_context(result["graph_context_id"]) + + def test_scoped_empty_budget_result_does_not_reconstruct_graph(self): + budget = RetrievalBudget(maximum_latency_ms=0) + with patch("trace_gc.retrieval.service.query_conflicts", wraps=query_conflicts) as conflicts: + context, result = self.context(self.request(["LEXICAL"], text="randomized", budget=budget)) + self.assertEqual(result["status"], "PARTIAL") + self.assertEqual(context["items"], []) + conflicts.assert_not_called() + + def test_scoped_verification_spends_the_remaining_work_budget(self): + discovery_cost = [] + + def measure(*args, meter=None): + discovery_cost.append(meter.used["cost_units"]) + _validate_context_items(*args, meter=meter) + + request = self.request(["LEXICAL"], text="randomized") + with patch("trace_gc.retrieval.service._validate_context_items", side_effect=measure): + self.r.retrieve(request) + budget = replace(self.budget, maximum_cost_units=discovery_cost[0]) + context, result = self.context(self.request(["LEXICAL"], text="randomized", budget=budget)) + self.assertEqual(result["status"], "PARTIAL") + self.assertEqual(context["items"], []) + lineage = self.c.get(result["lineage_id"], "retrieval-lineage") + self.assertEqual(lineage["discarded"][0]["reason"], "verification_budget") + self.assertLessEqual(lineage["cost_units"], budget.maximum_cost_units) + + def test_unscoped_materialization_remains_legacy_shaped(self): + ctx, _ = self.context(self.request(["LEXICAL"], text="randomized", research_domain_scope=None)) + self.assertNotIn("research_domain", ctx["items"][0]) + self.assertEqual(ctx["retrieved_edges"], []) + self.assertEqual(ctx["items"][0]["text"], self.c.get(self.f["evidence"]["e-method"])["quote"]) + + def test_descendant_selection_and_all_branch_semantics_are_explicit(self): + old_taxonomy = self.c.get(self.f["taxonomy_id"]) + taxonomy = deepcopy(old_taxonomy) + taxonomy.update(version=2, supersedes=self.f["taxonomy_id"], supersedes_hash=self.c.hash(self.f["taxonomy_id"])) + taxonomy["domains"].append({"id": "research:cell-biology", "label": "Cell biology", + "definition": "Synthetic hierarchy fixture for biological cells.", "parent_ids": ["research:biology"], "status": "ACTIVE"}) + taxonomy["domains"].sort(key=lambda row: row["id"]) + tax_id = self.c.put("research-domain-taxonomy", taxonomy) + source = self.f["sources"]["e-method"] + assignment = create_assignment(self.c, source_snapshot_id=source, taxonomy_id=tax_id, + domain_ids=["research:cell-biology", "research:chemistry"], review=taxonomy["review"], + classifier_id="synthetic-hierarchy", classifier_version="fixture-v1", supersedes=self.f["assignments"][source]) + snap = self.c.get(self.f["snapshot_id"]) + snap["classifications"]["assignments"][source] = assignment + snap["classifications"]["revision"] += 1 + self.replace_snapshot(snap) + parent = research_domain_scope(self.c, tax_id, ["research:biology"]) + ctx, _ = self.context(self.request(["LEXICAL"], text="randomized", research_domain_scope=parent)) + self.assertEqual(ctx["items"], []) + for selection in ({**parent, "include_descendants": True}, + {**parent, "include_descendants": True, "match": "ALL", "domain_ids": ["research:biology", "research:chemistry"]}): + with self.subTest(selection=selection): + ctx, _ = self.context(self.request(["LEXICAL"], text="randomized", research_domain_scope=selection)) + self.assertEqual([item["canonical_ref"] for item in ctx["items"]], [self.f["evidence"]["e-method"]]) + # The old pin does not silently reinterpret assignments in a new version. + ctx, _ = self.context(self.request(["LEXICAL"], text="randomized")) + self.assertEqual(ctx["items"], []) + + def test_direct_different_from_and_alias_proof_not_transitive_distinctions(self): + snap = self.c.get(self.f["snapshot_id"]) + statuses = self.f["adapter"].source_status + for edge, subject, predicate, object_ in ( + ("e-distinct", "Acme", "different_from", "Other"), + ("e-other-alias", "Other", "same_as", "Other-Alias"), + ("e-unrelated-distinction", "Other-Alias", "different_from", "Third")): + for node in (subject, object_): + snap["nodes"][node] = "Organization" + source = self.c.source("synthetic-" + edge, "1", "Synthetic identity proof: " + edge, scope=SCOPE) + evidence = self.c.evidence(source) + snap["source_epochs"][source] = 1 + statuses[source] = {"active": True, "permission": "READ", "epoch": 1, + "updated_at": "2026-09-27T00:00:00Z", "tombstone": False} + snap["assertions"][edge] = {"assertion": {"subject": subject, "predicate": predicate, "object": object_, "qualifiers": {}}, + "evidence_ids": [evidence], "prerequisites": [], "active": True, "revision": 1} + self.replace_snapshot(snap) + self.r.set_access_policy(demo_access(self.c, self.f["snapshot_id"])) + ctx, _ = self.context(self.request(["RELATION"], focus_entities=["Acme"], allowed_relation_types=["owns"])) + self.assertTrue({"e-owns", "e-distinct", "e-other-alias"} <= set(ctx["retrieved_edges"])) + self.assertNotIn("e-unrelated-distinction", ctx["retrieved_edges"]) + self.assertNotIn("Third", ctx["retrieved_nodes"]) + # Direct distinction closure does not grant the other entity membership. + ctx, _ = self.context(self.request(["ENTITY"], focus_entities=["Other"])) + self.assertEqual(ctx["items"], []) + + def replace_snapshot(self, body): + ref = self.c.put("graph-snapshot", body) + statuses = self.f["adapter"].source_status + adapter = InMemoryGraphAdapter(self.c, [ref], statuses) + self.f.update(adapter=adapter, snapshot_id=ref) + self.r.adapter = adapter + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_research_domain_semantic_boundary.py b/tests/test_research_domain_semantic_boundary.py new file mode 100644 index 0000000..ab5e2fd --- /dev/null +++ b/tests/test_research_domain_semantic_boundary.py @@ -0,0 +1,175 @@ +"""Semantic reranking keeps the exact domain view and rechecks current authority. + +All labels and model responses are synthetic fixtures. The reranker is called +through the existing pack/observation adapter; no live model is used. +""" +from __future__ import annotations + +from copy import deepcopy +import unittest + +from trace_gc.adapter import record_response +from trace_gc.compiler import compile_pack +from trace_gc.demo import fixture_response +from trace_gc.errors import ContractError +from trace_gc.programs import question +from trace_gc.replay import replay_retrieval +from trace_gc.retrieval.contracts import query, RetrievalBudget +from trace_gc.retrieval.domains import research_domain_scope +from trace_gc.retrieval.fixtures import demo_access, domain_corpus, SCOPE +from trace_gc.retrieval.reranker import JevReranker, validate_reranked_context +from trace_gc.retrieval.service import validate_context + + +class DomainSemanticBoundaryTests(unittest.TestCase): + def setUp(self): + self.f = domain_corpus() + self.c, self.r = self.f["catalog"], self.f["retriever"] + self.scope = research_domain_scope(self.c, self.f["taxonomy_id"], ["research:biology"]) + fact = self.c.get(self.f["snapshot_id"])["assertions"]["e-support"] + self.candidate = self.c.candidate(id_="candidate:domain-rerank", run_id="domain-rerank-fixture", + assertion=fact["assertion"], claim_id=self.f["claim_id"], evidence_ids=fact["evidence_ids"]) + request = query(requesting_component="upstream-synthesis", candidate_id=self.candidate, + security_scope=SCOPE, strategies=["LEXICAL"], text="improves", include_conflicts=False, + research_domain_scope=self.scope, + budget=RetrievalBudget(maximum_tokens=150000, maximum_latency_ms=20000, maximum_edges=100, + maximum_nodes=100, maximum_source_spans=100)) + self.result_id = self.r.retrieve(request) + self.calls = [] + + def execute(pack_id): + self.calls.append(pack_id) + return record_response(self.c, pack_id, fixture_response(self.c.get(pack_id, "pack"))) + self.reranker = JevReranker(execute) + + def rerank(self): + return self.reranker.rerank(self.r, self.result_id, candidate_id=self.candidate) + + def test_rerank_preserves_scope_revision_items_and_cross_domain_closure(self): + before = self.c.get(self.c.get(self.result_id)["graph_context_id"]) + reranked_id = self.rerank() + after_id = self.c.get(reranked_id)["graph_context_id"] + after = self.c.get(after_id) + validate_context(self.c, after_id, current_access=self.r.access_policy, + current_status=self.f["adapter"].source_status) + validate_reranked_context(self.c, after) + self.assertEqual(len(self.calls), 1) + self.assertEqual(after["research_domain_scope"], self.scope) + self.assertEqual(after["classification_identity"], before["classification_identity"]) + self.assertEqual({item["id"] for item in after["items"]}, {item["id"] for item in before["items"]}) + # The refuting evidence outside the requested label stays selected: ranking is not membership. + self.assertIn(self.f["evidence"]["e-refute"], after["selected_evidence_ids"]) + + def test_reranked_context_cannot_swap_the_domain_scope(self): + after = deepcopy(self.c.get(self.c.get(self.rerank())["graph_context_id"])) + after["research_domain_scope"] = {**self.scope, "domain_ids": ["research:physics"]} + with self.assertRaisesRegex(ContractError, "RERANK_OBSERVATION"): + validate_reranked_context(self.c, after) + + def test_source_revocation_after_retrieval_prevents_the_semantic_call(self): + self.f["adapter"].source_status[self.f["sources"]["e-support"]].update(active=False, epoch=2) + with self.assertRaisesRegex(ContractError, "RESEARCH_DOMAIN_SCOPE|ACCESS_DENIED"): + self.rerank() + self.assertEqual(self.calls, []) + + def test_revocation_during_rerank_prevents_returning_a_stale_context(self): + execute = self.reranker.execute + before = len(self.c.all("graph-context")) + + def execute_then_withdraw(pack_id): + observations = execute(pack_id) + self.f["adapter"].source_status[self.f["sources"]["e-refute"]].update(active=False, epoch=2) + return observations + + self.reranker.execute = execute_then_withdraw + with self.assertRaisesRegex(ContractError, "ACCESS_DENIED"): + self.rerank() + self.assertEqual(len(self.calls), 1) + self.assertEqual(len(self.c.all("graph-context")), before) + + def test_current_acl_revocation_prevents_the_semantic_call(self): + policy = deepcopy(self.r.access_policy) + del policy["grants"]["source:" + self.f["sources"]["e-support"]] + self.r.set_access_policy(policy) + with self.assertRaisesRegex(ContractError, "RESEARCH_DOMAIN_SCOPE|ACCESS_DENIED"): + self.rerank() + self.assertEqual(self.calls, []) + + def result_with_prerequisite(self): + fact = self.c.get(self.f["snapshot_id"])["assertions"]["e-owns"] + prerequisite = self.c.candidate(id_="candidate:prerequisite", run_id="domain-rerank-fixture", + assertion=fact["assertion"], claim_id=self.f["claim_id"], evidence_ids=fact["evidence_ids"]) + root = self.c.get(self.candidate, "candidate") + candidate = self.c.candidate(id_="candidate:with-prerequisite", run_id=root["run_id"], + assertion=root["assertion"], claim_id=root["claim_id"], evidence_ids=root["evidence_ids"], + prerequisites=[prerequisite]) + result = self.c.get(self.result_id, "retrieval-result") + request = self.c.get(result["query_id"], "retrieval-query") + return candidate, self.r.retrieve({**request, "candidate_id": candidate}) + + def test_prerequisite_endpoints_are_authorized_before_token_counting(self): + candidate, result_id = self.result_with_prerequisite() + policy = deepcopy(self.r.access_policy) + del policy["grants"]["node:Acme"] + self.r.set_access_policy(policy) + counted = [] + self.reranker.token_counter = lambda value: counted.append(value) or 0 + with self.assertRaisesRegex(ContractError, "ACCESS_DENIED"): + self.reranker.rerank(self.r, result_id, candidate_id=candidate) + self.assertEqual(counted, []) + self.assertEqual(self.calls, []) + + def test_authorization_is_rechecked_after_token_counting(self): + counted = [] + + def count(value): + counted.append(value) + self.f["adapter"].source_status[self.f["sources"]["e-support"]].update(active=False, epoch=2) + return 0 + + self.reranker.token_counter = count + with self.assertRaisesRegex(ContractError, "ACCESS_DENIED"): + self.rerank() + self.assertTrue(counted) + self.assertEqual(self.calls, []) + + def test_candidate_sources_are_authorized_before_upstream_embedding(self): + calls = [] + self.r.embedding.embed = lambda texts: calls.append(texts) or [] + result = self.c.get(self.result_id, "retrieval-result") + request = self.c.get(result["query_id"], "retrieval-query") + self.f["adapter"].source_status[self.f["sources"]["e-support"]].update(active=False, epoch=2) + with self.assertRaisesRegex(ContractError, "ACCESS_DENIED"): + self.r.retrieve({**request, "retrieval_strategy": ["VECTOR"]}) + self.assertEqual(calls, []) + + def test_replay_requires_current_access_to_original_context(self): + self.f["adapter"].source_status[self.f["sources"]["e-refute"]].update(active=False, epoch=2) + with self.assertRaisesRegex(ContractError, "ACCESS_DENIED"): + replay_retrieval(self.r, self.result_id, {}, synthesize=self.reranker.execute) + self.assertEqual(self.calls, []) + + def test_replay_omits_linked_receipt_when_its_full_pack_access_is_revoked(self): + candidate, result_id = self.result_with_prerequisite() + context_id = self.c.get(result_id, "retrieval-result")["graph_context_id"] + pack_id = compile_pack(self.c, id_="pack:replay-prerequisite", + run_id="domain-rerank-fixture", candidate_ids=[candidate], questions=[question(candidate, id_="support")], + snapshot_id=self.f["snapshot_id"], security_scope=SCOPE, + graph_context_ids=[context_id], source_retrieval_ids=[result_id]) + observation = record_response(self.c, pack_id, fixture_response(self.c.get(pack_id, "pack")))[0] + before = self.c.hash(observation) + no_grant = self.c.get(replay_retrieval(self.r, result_id, {}), "retrieval-replay") + self.assertEqual(no_grant["observation_hashes_preserved"], {}) + self.r.set_access_policy(demo_access(self.c, self.f["snapshot_id"])) + permitted = self.c.get(replay_retrieval(self.r, result_id, {}), "retrieval-replay") + self.assertEqual(permitted["observation_hashes_preserved"], {observation: before}) + policy = deepcopy(self.r.access_policy) + del policy["grants"]["node:Acme"] + self.r.set_access_policy(policy) + denied = self.c.get(replay_retrieval(self.r, result_id, {}), "retrieval-replay") + self.assertEqual(denied["observation_hashes_preserved"], {}) + self.assertEqual(self.c.hash(observation), before) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/domain_retrieval_schemas.py b/tools/domain_retrieval_schemas.py new file mode 100644 index 0000000..6a70dd0 --- /dev/null +++ b/tools/domain_retrieval_schemas.py @@ -0,0 +1,38 @@ +"""Additive, pinned research-domain query/context/replay contracts.""" +from copy import deepcopy + + +def extend(schemas): + s = {"type": "string", "minLength": 1} + h = {"type": "string", "pattern": "^[0-9a-f]{64}$"} + n = {"type": "integer", "minimum": 0} + b = {"type": "boolean"} + ids = {"type": "array", "items": s, "uniqueItems": True} + def obj(props): + return {"type": "object", "properties": deepcopy(props), "required": list(props), "additionalProperties": False} + def nullable(value): + return {"anyOf": [deepcopy(value), {"type": "null"}]} + scope = obj({"contract_version": {"const": 1}, "taxonomy_id": s, "taxonomy_hash": h, + "domain_ids": {"type": "array", "items": {"type": "string", "pattern": "^research:[a-z0-9][a-z0-9._-]*$"}, + "uniqueItems": True, "maxItems": 100}, + "match": {"enum": ["ANY", "ALL"]}, "include_unclassified": b, "include_descendants": b}) + # Optional for old serialized scopes: absence is literal-v1. New constructors + # explicitly select the audited identity-aware algorithm. Never rewrite a pin. + scope["properties"]["conflict_resolution"] = {"enum": ["literal-v1", "authorized-identity-v1"]} + identity = obj({"contract_version": {"const": 1}, "revision": n, "hash": h, "migrated": b}) + metadata = obj({"version": {"const": "authorized-research-domain-selection-v1"}, "scope_hash": h, + "classification_hash": h, "anchor_assertion_ids": ids, "closure_assertion_ids": ids, + "source_assignments": {"type": "object", "additionalProperties": nullable(s)}}) + schemas["research-domain-scope"] = deepcopy(scope) + schemas["classification-read-identity"] = deepcopy(identity) + for kind in ("retrieval-query", "retrieval-plan"): + schemas[kind]["properties"]["research_domain_scope"] = nullable(scope) + for kind in ("graph-context", "retrieval-lineage", "graphrag-answer"): + schemas[kind]["properties"]["research_domain_scope"] = nullable(scope) + schemas[kind]["properties"]["classification_identity"] = deepcopy(identity) + for kind in ("graph-context", "graphrag-answer"): + schemas[kind]["properties"]["items"]["items"]["properties"]["research_domain"] = deepcopy(metadata) + for key in ("original_classification_identity", "replayed_classification_identity"): + schemas["retrieval-replay"]["properties"][key] = deepcopy(identity) + schemas["retrieval-replay"]["properties"]["original_research_domain_scope"] = nullable(scope) + schemas["retrieval-replay"]["properties"]["replayed_research_domain_scope"] = nullable(scope) diff --git a/tools/retrieval_schemas.py b/tools/retrieval_schemas.py index 3415d70..128639c 100644 --- a/tools/retrieval_schemas.py +++ b/tools/retrieval_schemas.py @@ -88,6 +88,18 @@ def nullable(item): "original_selected_ids": IDS, "replayed_selected_ids": IDS, "added_ids": IDS, "removed_ids": IDS, "observation_hashes_preserved": mapping(H), "new_observation_ids": IDS, "synthesis_comparison": {"type": "object"}, "authorization_granted": {"const": False}, "created_at": T}) + schemas["retrieval-replay"]["properties"]["replay_access_id"] = S + schemas["retrieval-replay"]["allOf"] = [{ + "if": {"required": ["replay_access_id"]}, + "then": {"properties": {"synthesis_comparison": {"oneOf": [ + obj({"observation_ids": IDS}), + obj({"status": {"const": "NOT_RUN"}, "reason": {"const": "No synthesis executor supplied."}}), + ]}}}, + }, { + "if": {"anyOf": [{"required": [f"{side}_{field}"]} for side in ("original", "replayed") + for field in ("classification_identity", "research_domain_scope")]}, + "then": {"required": ["replay_access_id"]}, + }] schemas["retrieval-evaluation"] = obj({"version": S, "dataset_hash": H, "split": S, "label_origin": S, "metrics": {"type": "object"}, "configuration": {"type": "object"}, "result_ids": IDS, "production_qualified": {"const": False}, "created_at": T}) @@ -102,3 +114,6 @@ def nullable(item): q = schemas["pack"]["properties"]["questions"]["items"] q["properties"]["task"]["enum"].append("GRAPH_RELEVANCE") q["properties"]["context_item_id"] = S + + from domain_retrieval_schemas import extend as extend_domain_retrieval + extend_domain_retrieval(schemas) diff --git a/trace_gc/compiler.py b/trace_gc/compiler.py index 6260f95..f90ae3e 100644 --- a/trace_gc/compiler.py +++ b/trace_gc/compiler.py @@ -156,6 +156,12 @@ def trace(path: str, ref: str, locator: str, version: str = "identity-v1") -> No state["graph_context"].append({"context_id": ref, "items": deepcopy(context["items"]), "instruction_authority": False}) trace(f"/graph_context/{i}/items", ref, "/items") + if context.get("research_domain_scope") is not None: + # Carry the selected topic and revision without adding taxonomy + # review material to the evidence closure. + for field in ("classification_identity", "research_domain_scope"): + state["graph_context"][i][field] = deepcopy(context[field]) + trace(f"/graph_context/{i}/{field}", ref, f"/{field}") return state,closed,traces def wire_request(pack: dict[str, Any]) -> bytes: @@ -202,7 +208,9 @@ def compile_pack(catalog: Catalog, *, id_: str, run_id: str, candidate_ids: list transformation: str = "identity-v1", token_counter: Callable[[Any],int] | None = None, tokenizer_version: str = "utf8-byte-estimate-v1", request_cap: int = 64000, state_longest_cap: int = 32000, graph_context_ids: list[str] | None = None, - source_retrieval_ids: list[str] | None = None, model_profile: dict | None = None) -> str: + source_retrieval_ids: list[str] | None = None, model_profile: dict | None = None, + current_graph_access: dict[str, Any] | None = None, + source_status: dict[str, Any] | None = None) -> str: from .semantic_profile import validate_model, adapter_for validate_model(model_version, model_profile) require(len(candidate_ids) == len(set(candidate_ids)) and bool(candidate_ids),"DUPLICATE_ID","candidate roots") @@ -224,6 +232,11 @@ def compile_pack(catalog: Catalog, *, id_: str, run_id: str, candidate_ids: list pack.update(lineage_fields(catalog, graph_context_ids or [], source_retrieval_ids or [], closed["hash"])) pack["materializer_version"] = "materializer-v1+graph-v1" pack["packing_version"] = "minimum-source-graph-v1:" + pack["retrieval_fingerprint"] + require(token_counter is None or (current_graph_access is not None and source_status is not None), "SOURCE_STATUS_CAPABILITY", + "retrieval pack token counting requires live graph authorization") + if current_graph_access is not None: + from .retrieval.integration import validate_pack_lineage + validate_pack_lineage(catalog, pack, current_access=current_graph_access, current_status=source_status) counter = token_counter or byte_estimate pack["budget"]={"state_tokens":counter(state),"question_tokens":{q["id"]:counter(q) for q in questions}, "request_cap":request_cap,"state_longest_cap":state_longest_cap,"measured":token_counter is not None} diff --git a/trace_gc/data/schemas/classification-read-identity.schema.json b/trace_gc/data/schemas/classification-read-identity.schema.json new file mode 100644 index 0000000..7c8eddc --- /dev/null +++ b/trace_gc/data/schemas/classification-read-identity.schema.json @@ -0,0 +1,29 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:trace-gc:0.3.0:classification-read-identity", + "title": "TRACE-GC classification-read-identity v0.3.0", + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "revision": { + "type": "integer", + "minimum": 0 + }, + "hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "migrated": { + "type": "boolean" + } + }, + "required": [ + "contract_version", + "revision", + "hash", + "migrated" + ], + "additionalProperties": false +} diff --git a/trace_gc/data/schemas/graph-context.schema.json b/trace_gc/data/schemas/graph-context.schema.json index 9d0b3a5..bc95939 100644 --- a/trace_gc/data/schemas/graph-context.schema.json +++ b/trace_gc/data/schemas/graph-context.schema.json @@ -282,6 +282,61 @@ }, "instruction_authority": { "const": false + }, + "research_domain": { + "type": "object", + "properties": { + "version": { + "const": "authorized-research-domain-selection-v1" + }, + "scope_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "classification_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "anchor_assertion_ids": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "uniqueItems": true + }, + "closure_assertion_ids": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "uniqueItems": true + }, + "source_assignments": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "type": "null" + } + ] + } + } + }, + "required": [ + "version", + "scope_hash", + "classification_hash", + "anchor_assertion_ids", + "closure_assertion_ids", + "source_assignments" + ], + "additionalProperties": false } }, "required": [ @@ -487,6 +542,92 @@ "reranking_base_context_id": { "type": "string", "minLength": 1 + }, + "research_domain_scope": { + "anyOf": [ + { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "taxonomy_id": { + "type": "string", + "minLength": 1 + }, + "taxonomy_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "domain_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^research:[a-z0-9][a-z0-9._-]*$" + }, + "uniqueItems": true, + "maxItems": 100 + }, + "match": { + "enum": [ + "ANY", + "ALL" + ] + }, + "include_unclassified": { + "type": "boolean" + }, + "include_descendants": { + "type": "boolean" + }, + "conflict_resolution": { + "enum": [ + "literal-v1", + "authorized-identity-v1" + ] + } + }, + "required": [ + "contract_version", + "taxonomy_id", + "taxonomy_hash", + "domain_ids", + "match", + "include_unclassified", + "include_descendants" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "classification_identity": { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "revision": { + "type": "integer", + "minimum": 0 + }, + "hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "migrated": { + "type": "boolean" + } + }, + "required": [ + "contract_version", + "revision", + "hash", + "migrated" + ], + "additionalProperties": false } }, "required": [ diff --git a/trace_gc/data/schemas/graphrag-answer.schema.json b/trace_gc/data/schemas/graphrag-answer.schema.json index 7bd63a0..a41af4c 100644 --- a/trace_gc/data/schemas/graphrag-answer.schema.json +++ b/trace_gc/data/schemas/graphrag-answer.schema.json @@ -239,6 +239,61 @@ }, "instruction_authority": { "const": false + }, + "research_domain": { + "type": "object", + "properties": { + "version": { + "const": "authorized-research-domain-selection-v1" + }, + "scope_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "classification_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "anchor_assertion_ids": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "uniqueItems": true + }, + "closure_assertion_ids": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "uniqueItems": true + }, + "source_assignments": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "type": "null" + } + ] + } + } + }, + "required": [ + "version", + "scope_hash", + "classification_hash", + "anchor_assertion_ids", + "closure_assertion_ids", + "source_assignments" + ], + "additionalProperties": false } }, "required": [ @@ -331,6 +386,92 @@ "created_at": { "type": "string", "format": "date-time" + }, + "research_domain_scope": { + "anyOf": [ + { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "taxonomy_id": { + "type": "string", + "minLength": 1 + }, + "taxonomy_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "domain_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^research:[a-z0-9][a-z0-9._-]*$" + }, + "uniqueItems": true, + "maxItems": 100 + }, + "match": { + "enum": [ + "ANY", + "ALL" + ] + }, + "include_unclassified": { + "type": "boolean" + }, + "include_descendants": { + "type": "boolean" + }, + "conflict_resolution": { + "enum": [ + "literal-v1", + "authorized-identity-v1" + ] + } + }, + "required": [ + "contract_version", + "taxonomy_id", + "taxonomy_hash", + "domain_ids", + "match", + "include_unclassified", + "include_descendants" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "classification_identity": { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "revision": { + "type": "integer", + "minimum": 0 + }, + "hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "migrated": { + "type": "boolean" + } + }, + "required": [ + "contract_version", + "revision", + "hash", + "migrated" + ], + "additionalProperties": false } }, "required": [ diff --git a/trace_gc/data/schemas/research-domain-scope.schema.json b/trace_gc/data/schemas/research-domain-scope.schema.json new file mode 100644 index 0000000..4059738 --- /dev/null +++ b/trace_gc/data/schemas/research-domain-scope.schema.json @@ -0,0 +1,56 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:trace-gc:0.3.0:research-domain-scope", + "title": "TRACE-GC research-domain-scope v0.3.0", + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "taxonomy_id": { + "type": "string", + "minLength": 1 + }, + "taxonomy_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "domain_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^research:[a-z0-9][a-z0-9._-]*$" + }, + "uniqueItems": true, + "maxItems": 100 + }, + "match": { + "enum": [ + "ANY", + "ALL" + ] + }, + "include_unclassified": { + "type": "boolean" + }, + "include_descendants": { + "type": "boolean" + }, + "conflict_resolution": { + "enum": [ + "literal-v1", + "authorized-identity-v1" + ] + } + }, + "required": [ + "contract_version", + "taxonomy_id", + "taxonomy_hash", + "domain_ids", + "match", + "include_unclassified", + "include_descendants" + ], + "additionalProperties": false +} diff --git a/trace_gc/data/schemas/retrieval-lineage.schema.json b/trace_gc/data/schemas/retrieval-lineage.schema.json index 5476cce..7bafdd1 100644 --- a/trace_gc/data/schemas/retrieval-lineage.schema.json +++ b/trace_gc/data/schemas/retrieval-lineage.schema.json @@ -253,6 +253,92 @@ "created_at": { "type": "string", "format": "date-time" + }, + "research_domain_scope": { + "anyOf": [ + { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "taxonomy_id": { + "type": "string", + "minLength": 1 + }, + "taxonomy_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "domain_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^research:[a-z0-9][a-z0-9._-]*$" + }, + "uniqueItems": true, + "maxItems": 100 + }, + "match": { + "enum": [ + "ANY", + "ALL" + ] + }, + "include_unclassified": { + "type": "boolean" + }, + "include_descendants": { + "type": "boolean" + }, + "conflict_resolution": { + "enum": [ + "literal-v1", + "authorized-identity-v1" + ] + } + }, + "required": [ + "contract_version", + "taxonomy_id", + "taxonomy_hash", + "domain_ids", + "match", + "include_unclassified", + "include_descendants" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "classification_identity": { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "revision": { + "type": "integer", + "minimum": 0 + }, + "hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "migrated": { + "type": "boolean" + } + }, + "required": [ + "contract_version", + "revision", + "hash", + "migrated" + ], + "additionalProperties": false } }, "required": [ diff --git a/trace_gc/data/schemas/retrieval-plan.schema.json b/trace_gc/data/schemas/retrieval-plan.schema.json index ff62cc0..0bac34e 100644 --- a/trace_gc/data/schemas/retrieval-plan.schema.json +++ b/trace_gc/data/schemas/retrieval-plan.schema.json @@ -198,6 +198,66 @@ "created_at": { "type": "string", "format": "date-time" + }, + "research_domain_scope": { + "anyOf": [ + { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "taxonomy_id": { + "type": "string", + "minLength": 1 + }, + "taxonomy_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "domain_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^research:[a-z0-9][a-z0-9._-]*$" + }, + "uniqueItems": true, + "maxItems": 100 + }, + "match": { + "enum": [ + "ANY", + "ALL" + ] + }, + "include_unclassified": { + "type": "boolean" + }, + "include_descendants": { + "type": "boolean" + }, + "conflict_resolution": { + "enum": [ + "literal-v1", + "authorized-identity-v1" + ] + } + }, + "required": [ + "contract_version", + "taxonomy_id", + "taxonomy_hash", + "domain_ids", + "match", + "include_unclassified", + "include_descendants" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] } }, "required": [ diff --git a/trace_gc/data/schemas/retrieval-query.schema.json b/trace_gc/data/schemas/retrieval-query.schema.json index 5bda4f5..d391acb 100644 --- a/trace_gc/data/schemas/retrieval-query.schema.json +++ b/trace_gc/data/schemas/retrieval-query.schema.json @@ -300,6 +300,66 @@ "created_at": { "type": "string", "format": "date-time" + }, + "research_domain_scope": { + "anyOf": [ + { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "taxonomy_id": { + "type": "string", + "minLength": 1 + }, + "taxonomy_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "domain_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^research:[a-z0-9][a-z0-9._-]*$" + }, + "uniqueItems": true, + "maxItems": 100 + }, + "match": { + "enum": [ + "ANY", + "ALL" + ] + }, + "include_unclassified": { + "type": "boolean" + }, + "include_descendants": { + "type": "boolean" + }, + "conflict_resolution": { + "enum": [ + "literal-v1", + "authorized-identity-v1" + ] + } + }, + "required": [ + "contract_version", + "taxonomy_id", + "taxonomy_hash", + "domain_ids", + "match", + "include_unclassified", + "include_descendants" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] } }, "required": [ diff --git a/trace_gc/data/schemas/retrieval-replay.schema.json b/trace_gc/data/schemas/retrieval-replay.schema.json index a03c3d7..ec69913 100644 --- a/trace_gc/data/schemas/retrieval-replay.schema.json +++ b/trace_gc/data/schemas/retrieval-replay.schema.json @@ -83,6 +83,182 @@ "created_at": { "type": "string", "format": "date-time" + }, + "replay_access_id": { + "type": "string", + "minLength": 1 + }, + "original_classification_identity": { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "revision": { + "type": "integer", + "minimum": 0 + }, + "hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "migrated": { + "type": "boolean" + } + }, + "required": [ + "contract_version", + "revision", + "hash", + "migrated" + ], + "additionalProperties": false + }, + "replayed_classification_identity": { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "revision": { + "type": "integer", + "minimum": 0 + }, + "hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "migrated": { + "type": "boolean" + } + }, + "required": [ + "contract_version", + "revision", + "hash", + "migrated" + ], + "additionalProperties": false + }, + "original_research_domain_scope": { + "anyOf": [ + { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "taxonomy_id": { + "type": "string", + "minLength": 1 + }, + "taxonomy_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "domain_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^research:[a-z0-9][a-z0-9._-]*$" + }, + "uniqueItems": true, + "maxItems": 100 + }, + "match": { + "enum": [ + "ANY", + "ALL" + ] + }, + "include_unclassified": { + "type": "boolean" + }, + "include_descendants": { + "type": "boolean" + }, + "conflict_resolution": { + "enum": [ + "literal-v1", + "authorized-identity-v1" + ] + } + }, + "required": [ + "contract_version", + "taxonomy_id", + "taxonomy_hash", + "domain_ids", + "match", + "include_unclassified", + "include_descendants" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "replayed_research_domain_scope": { + "anyOf": [ + { + "type": "object", + "properties": { + "contract_version": { + "const": 1 + }, + "taxonomy_id": { + "type": "string", + "minLength": 1 + }, + "taxonomy_hash": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "domain_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^research:[a-z0-9][a-z0-9._-]*$" + }, + "uniqueItems": true, + "maxItems": 100 + }, + "match": { + "enum": [ + "ANY", + "ALL" + ] + }, + "include_unclassified": { + "type": "boolean" + }, + "include_descendants": { + "type": "boolean" + }, + "conflict_resolution": { + "enum": [ + "literal-v1", + "authorized-identity-v1" + ] + } + }, + "required": [ + "contract_version", + "taxonomy_id", + "taxonomy_hash", + "domain_ids", + "match", + "include_unclassified", + "include_descendants" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] } }, "required": [ @@ -102,5 +278,86 @@ "authorization_granted", "created_at" ], - "additionalProperties": false + "additionalProperties": false, + "allOf": [ + { + "if": { + "required": [ + "replay_access_id" + ] + }, + "then": { + "properties": { + "synthesis_comparison": { + "oneOf": [ + { + "type": "object", + "properties": { + "observation_ids": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "uniqueItems": true + } + }, + "required": [ + "observation_ids" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "status": { + "const": "NOT_RUN" + }, + "reason": { + "const": "No synthesis executor supplied." + } + }, + "required": [ + "status", + "reason" + ], + "additionalProperties": false + } + ] + } + } + } + }, + { + "if": { + "anyOf": [ + { + "required": [ + "original_classification_identity" + ] + }, + { + "required": [ + "original_research_domain_scope" + ] + }, + { + "required": [ + "replayed_classification_identity" + ] + }, + { + "required": [ + "replayed_research_domain_scope" + ] + } + ] + }, + "then": { + "required": [ + "replay_access_id" + ] + } + } + ] } diff --git a/trace_gc/replay.py b/trace_gc/replay.py index eb783e0..b0eab88 100644 --- a/trace_gc/replay.py +++ b/trace_gc/replay.py @@ -9,6 +9,14 @@ from .ledger import make_bundle from .validation import validate_bundle +RETRIEVAL_REPLAY_PARAMETERS = frozenset({ + "retrieval_strategy", "hop_limit", "budget", "include_provenance", + "include_conflicts", "include_historical", "include_superseded", + "ranking_strategy", "graph_version", "temporal_scope", "mode", + "allowed_relation_types", "excluded_relation_types", "ontology_scope", + "community_scope", "source_scope", "research_domain_scope", +}) + def replay_analysis_policy(bundle: dict[str,Any], policy: dict[str,Any], *, trust=None, at: str | None=None) -> dict[str,Any]: """Return an explicitly unsigned, analysis-only branch. Never authorize writes. @@ -40,34 +48,66 @@ def replay_retrieval(retriever, original_result_id: str, changes: dict[str, Any] """Counterfactual retrieval branch; original observations and graph remain intact. ``synthesize(new_result_id)`` may invoke the existing compiler/adapter/resolver - to create NEW observations. This API never grants publication authority. + to create NEW observations. The receipt comparison is derived from the + authorized observations emitted by the callback. This API never grants publication authority. Current permissions still apply to historical snapshots. """ from .compiler import now from .retrieval.contracts import VERSION + from .retrieval.integration import context_observations, observation_sources_readable, observation_uses_result, validate_record + from .retrieval.security import AccessFilter + from .domain_publication import classification_identity c = retriever.catalog + require(set(changes) <= RETRIEVAL_REPLAY_PARAMETERS, "REPLAY_SCOPE", + "replay cannot change tenant, candidate or requesting role") + validate_record(c, c.record(original_result_id)) original = c.get(original_result_id, "retrieval-result") context = c.get(original["graph_context_id"], "graph-context") + retriever.validate_live_context(original["graph_context_id"]) request = c.get(original["query_id"], "retrieval-query") - allowed = {"retrieval_strategy", "hop_limit", "budget", "include_provenance", "include_conflicts", - "include_historical", "include_superseded", "ranking_strategy", "graph_version", "temporal_scope", "mode", - "allowed_relation_types", "excluded_relation_types", "ontology_scope", "community_scope", "source_scope"} - require(set(changes) <= allowed, "REPLAY_SCOPE", "replay cannot change tenant, candidate or requesting role") before = {r["id"]: r["hash"] for r in c.all("observation")} request.update(graph_version=context["graph_version"], created_at=now()) request.update(deepcopy(changes)) result_id = retriever.retrieve(request) new_result = c.get(result_id, "retrieval-result") new_context = c.get(new_result["graph_context_id"], "graph-context") - comparison = synthesize(result_id) if synthesize is not None else {"status": "NOT_RUN", "reason": "No synthesis executor supplied."} + require(context["graph_version"] != new_context["graph_version"] or + context["snapshot_id"] == new_context["snapshot_id"], "DOMAIN_REVISION", + "the same graph version must resolve to the same snapshot") + if synthesize is not None: + retriever.validate_live_context(new_result["graph_context_id"]) + synthesize(result_id) after = {r["id"]: r["hash"] for r in c.all("observation")} require(all(after.get(ref) == value for ref, value in before.items()), "REPLAY_OBSERVATION_CHANGED", "original receipts are immutable") + retriever.validate_live_context(original["graph_context_id"]) + statuses = retriever.validate_live_context(new_result["graph_context_id"]) + access = AccessFilter(retriever.access_policy, c, statuses) + + original_refs = context_observations(context) + preserved = {} + for ref, value in before.items(): + linked = observation_uses_result(c, ref, original_result_id, context["security_scope"]) + if (linked or ref in original_refs) and access.decision(ref) and observation_sources_readable(c, ref, access): + preserved[ref] = value + new_refs = sorted(set(after) - set(before)) + require(all(access.decision(ref) and observation_uses_result(c, ref, result_id, new_context["security_scope"]) and + observation_sources_readable(c, ref, access) for ref in new_refs), + "REPLAY_OBSERVATION_LINEAGE", "new receipt requires current decision access and replayed result lineage") + comparison = {"observation_ids": new_refs} if synthesize is not None else { + "status": "NOT_RUN", "reason": "No synthesis executor supplied."} old_ids = {i["id"] for i in context["items"]} new_ids = {i["id"] for i in new_context["items"]} - return c.put("retrieval-replay", {"version": VERSION, "original_result_id": original_result_id, - "replayed_result_id": result_id, "changed_parameters": deepcopy(changes), + receipt = {"version": VERSION, "original_result_id": original_result_id, + "replayed_result_id": result_id, "replay_access_id": c.put("graph-access", access.policy), + "changed_parameters": deepcopy(changes), "original_graph_version": context["graph_version"], "replayed_graph_version": new_context["graph_version"], + "original_classification_identity": context.get("classification_identity", classification_identity(c.get(context["snapshot_id"], "graph-snapshot"))), + "replayed_classification_identity": new_context["classification_identity"], + "original_research_domain_scope": c.get(original["query_id"], "retrieval-query").get("research_domain_scope"), + "replayed_research_domain_scope": new_context["research_domain_scope"], "original_selected_ids": sorted(old_ids), "replayed_selected_ids": sorted(new_ids), "added_ids": sorted(new_ids-old_ids), "removed_ids": sorted(old_ids-new_ids), - "observation_hashes_preserved": before, "new_observation_ids": sorted(set(after)-set(before)), - "synthesis_comparison": comparison, "authorization_granted": False, "created_at": now()}) + "observation_hashes_preserved": preserved, "new_observation_ids": new_refs, + "synthesis_comparison": comparison, "authorization_granted": False, "created_at": now()} + validate_record(c, {"kind": "retrieval-replay", "body": receipt}) + return c.put("retrieval-replay", receipt) diff --git a/trace_gc/retrieval/contracts.py b/trace_gc/retrieval/contracts.py index 19d5939..07c981a 100644 --- a/trace_gc/retrieval/contracts.py +++ b/trace_gc/retrieval/contracts.py @@ -1,5 +1,6 @@ """Versioned retrieval contracts. Scores are utilities, never calibrated truth.""" from __future__ import annotations +from copy import deepcopy from dataclasses import asdict, dataclass, field from typing import Any from ..canonical import digest @@ -66,7 +67,8 @@ def to_dict(self) -> dict[str, int]: def query(*, requesting_component: str, security_scope: str, focus_entities: list[str] | None = None, text: str = "", candidate_id: str | None = None, decision_id: str | None = None, strategies: list[str] | None = None, budget: RetrievalBudget | None = None, - mode: str = "BALANCED_EVIDENCE", **changes: Any) -> dict[str, Any]: + mode: str = "BALANCED_EVIDENCE", research_domain_scope: dict[str, Any] | None = None, + **changes: Any) -> dict[str, Any]: limits = budget or RetrievalBudget() body = {"version": VERSION, "requesting_component": requesting_component, "security_scope": security_scope, "candidate_id": candidate_id, "decision_id": decision_id, @@ -74,6 +76,7 @@ def query(*, requesting_component: str, security_scope: str, focus_entities: lis "target_information": [], "hop_limit": min(1, limits.maximum_hops), "allowed_relation_types": [], "excluded_relation_types": [], "temporal_scope": {"as_of": None, "valid_at": None, "before_source": None}, "graph_version": None, "ontology_scope": [], "source_scope": [], "community_scope": [], + "research_domain_scope": deepcopy(research_domain_scope), "include_provenance": True, "include_conflicts": True, "include_historical": False, "include_superseded": False, "retrieval_strategy": ["ENTITY", "NEIGHBORHOOD", "EVIDENCE", "CONFLICT"] if strategies is None else list(strategies), "ranking_strategy": "evidence-utility-v1", "mode": mode, "budget": limits.to_dict(), diff --git a/trace_gc/retrieval/domains.py b/trace_gc/retrieval/domains.py new file mode 100644 index 0000000..ba4bd8a --- /dev/null +++ b/trace_gc/retrieval/domains.py @@ -0,0 +1,410 @@ +"""One authorized research-domain predicate for every retrieval candidate channel. + +A scope chooses topical anchors. Required, authorized evidence/identity/conflict +closure travels atomically with an anchor; it is not used as an independent +out-of-domain lexical/vector candidate. Labels never confer permission or truth. +""" +from __future__ import annotations + +from collections import defaultdict, deque +from copy import deepcopy +from typing import Any + +from ..canonical import digest +from ..constraints import normalize +from ..catalog import Catalog +from ..domains import verify_taxonomy +from ..errors import require +from ..schema import validate + +DOMAIN_SELECTION_VERSION = "authorized-research-domain-selection-v1" +LITERAL_CONFLICTS = "literal-v1" +AUTHORIZED_IDENTITY_CONFLICTS = "authorized-identity-v1" + + +def identity_aware_scope(query: dict[str, Any]) -> bool: + """Missing selection pins preserve previously serialized literal semantics.""" + scope = query.get("research_domain_scope") + mode = (scope or {}).get("conflict_resolution", LITERAL_CONFLICTS) + require(mode in {LITERAL_CONFLICTS, AUTHORIZED_IDENTITY_CONFLICTS}, + "RESEARCH_DOMAIN_SCOPE", "unknown conflict-resolution implementation") + return scope is not None and mode == AUTHORIZED_IDENTITY_CONFLICTS + + +def require_live_scope(query: dict[str, Any]) -> None: + """New scoped searches always retain authorized identity-based refutations.""" + require(query.get("research_domain_scope") is None or identity_aware_scope(query), + "RESEARCH_DOMAIN_SCOPE", "live scoped retrieval requires authorized-identity-v1") + + +def research_domain_scope(catalog: Catalog, taxonomy_id: str, domain_ids: list[str], *, + match: str = "ANY", include_unclassified: bool = False, + include_descendants: bool = False, + conflict_resolution: str = AUTHORIZED_IDENTITY_CONFLICTS) -> dict[str, Any]: + body = {"contract_version": 1, "taxonomy_id": taxonomy_id, "taxonomy_hash": catalog.hash(taxonomy_id), + "domain_ids": sorted(set(domain_ids)), "match": match, + "include_unclassified": include_unclassified, "include_descendants": include_descendants, + "conflict_resolution": conflict_resolution} + validate_scope(catalog, body) + return body + + +def _active_scope_terms(catalog: Catalog, scope: dict[str, Any]) -> dict[str, dict[str, Any]]: + validate("research-domain-scope", scope) + require(scope["domain_ids"] == sorted(set(scope["domain_ids"])), "RESEARCH_DOMAIN_SCOPE", "domain IDs must be canonical") + require(bool(scope["domain_ids"]) or scope["include_unclassified"], + "RESEARCH_DOMAIN_SCOPE", "an empty selection must explicitly request unclassified material") + taxonomy = verify_taxonomy(catalog, scope["taxonomy_id"]) + require(catalog.hash(scope["taxonomy_id"]) == scope["taxonomy_hash"], + "RESEARCH_DOMAIN_SCOPE", "taxonomy hash does not match the requested immutable version") + require(taxonomy["review"]["status"] == "APPROVED", "RESEARCH_DOMAIN_SCOPE", "query taxonomy has not been reviewed") + active = {row["id"]: row for row in taxonomy["domains"] if row["status"] == "ACTIVE"} + require(set(scope["domain_ids"]) <= set(active), "RESEARCH_DOMAIN_SCOPE", "unknown or retired domain ID") + return active + + +def _scope_branches(scope: dict[str, Any], active: dict[str, dict[str, Any]], work) -> list[set[str]]: + requested = scope["domain_ids"] + if not requested: + return [] + work(len(requested)) + branches = [set(requested)] if scope["match"] == "ANY" else [{ref} for ref in requested] + if not scope["include_descendants"]: + return branches + children: dict[str, list[str]] = defaultdict(list) + for ref, row in active.items(): + work(1 + len(row["parent_ids"])) + for parent in row["parent_ids"]: + children[parent].append(ref) + for branch in branches: + pending = deque(sorted(branch)) + while pending: + descendants = children[pending.popleft()] + work(1 + len(descendants)) + for ref in descendants: + if ref not in branch: + branch.add(ref) + pending.append(ref) + return branches + + +def validate_scope(catalog: Catalog, scope: dict[str, Any] | None, *, expand: bool = True) -> set[str]: + if scope is None: + return set() + active = _active_scope_terms(catalog, scope) + if not expand: + return set(scope["domain_ids"]) + return set().union(*_scope_branches(scope, active, lambda _: None)) + + +class ResearchDomainSelection: + """Trusted per-read selection derived from an already ACL-filtered graph. + + The taxonomy pin is exact: unrelated or differently versioned taxonomies do + not silently share an ID namespace. A later taxonomy requires explicit + reclassification or an explicit query for its predecessor version. + """ + def __init__(self, view, access, query: dict[str, Any], edges: dict[str, Any], + conflicts: list[list[str]], meter=None): + self.view, self.access, self.query = view, access, query + self.scope = deepcopy(query.get("research_domain_scope")) + self.enabled = self.scope is not None + self._identity_aware = identity_aware_scope(query) + self._identity_predicates: dict[str, str] = {} + self.edges, self.conflicts, self.meter = edges, conflicts, meter + self._branches = _scope_branches(self.scope, _active_scope_terms(view.catalog, self.scope), self.work) if self.enabled else [] + self.selected_domains = set().union(*self._branches) + self._source_rows: dict[str, dict[str, Any]] = {} + self._edge_sources: dict[str, set[str]] = {} + self._incident: dict[str, set[str]] = defaultdict(set) + self._evidence_edges: dict[str, set[str]] = defaultdict(set) + self._identity_incident: dict[str, set[str]] = defaultdict(set) + self._equivalence_incident: dict[str, set[str]] = defaultdict(set) + self._conflict_neighbors: dict[str, set[str]] = defaultdict(set) + self._same_as: dict[str, str] = {} + self._closure_cache: dict[tuple[frozenset[str], bool], tuple[frozenset[str], bool]] = {} + self._unavailable: set[str] = set() + self._node_seed_cache: dict[str, set[str]] = {} + self._candidate_cache: dict[tuple, bool] = {} + self.contributing_edges: set[str] = set(edges) if not self.enabled else set() + self.allowed_edges = edges + if not self.enabled: + return + c = view.catalog + snapshot = view.snapshot + self._schema_id, self._nodes = snapshot["schema_id"], snapshot["nodes"] + self._relations = c.get(self._schema_id, "schema")["relations"] + for source_id in snapshot["source_epochs"]: + self.work() + # Never examine a denied source's assignment to choose membership. + row = view.source_classification(source_id, access) + if row is not None: + self._source_rows[source_id] = row + for ref, fact in edges.items(): + self.work() + # Defense in depth: callers cannot supply an unfiltered edge map. + require(access.edge(ref, fact), "ACCESS_DENIED", "domain selection requires authorized current evidence") + a = fact["assertion"] + predicate = normalize(a, self._relations)[1] if self._identity_aware else a["predicate"] + self._identity_predicates[ref] = predicate + usable_identity = fact["active"] or not self._identity_aware + sources = {c.get(e, "evidence")["source_snapshot_id"] for e in fact["evidence_ids"]} + self._edge_sources[ref] = sources + for node in (a["subject"], a["object"]): + self._incident[node].add(ref) + self._same_as.setdefault(node, node) + if usable_identity and predicate in {"same_as", "different_from"}: + self._identity_incident[node].add(ref) + if usable_identity and predicate == "same_as": + self._equivalence_incident[node].add(ref) + for evidence_id in fact["evidence_ids"]: + self._evidence_edges[evidence_id].add(ref) + if self._matches_anchor_filters(ref) and self.contributes(sources): + self.contributing_edges.add(ref) + if usable_identity and predicate == "same_as": + left, right = self._root(a["subject"]), self._root(a["object"]) + self._same_as[max(left, right)] = min(left, right) + self._equivalent_nodes: dict[str, set[str]] = defaultdict(set) + for node in self._same_as: + self._equivalent_nodes[self._root(node)].add(node) + for pair in conflicts: + for left in pair: + self._conflict_neighbors[left].update(set(pair) - {left}) + self._unavailable = self._unprovable_edges() + if self._unavailable: + # An anchor whose required proof cannot be fully produced under current + # authority is excluded whole, never returned with a truncated proof. + for ref in sorted(self.contributing_edges): + if self._closure(frozenset({ref}), probe=True)[1]: + self.contributing_edges.discard(ref) + self._node_seed_cache.clear() + included = self.closure(self.contributing_edges) + self.allowed_edges = {ref: fact for ref, fact in edges.items() if ref in included} + + def work(self, count: int = 1) -> None: + if self.meter is not None: + self.meter.work(count) + + def _root(self, node: str) -> str: + root = self._same_as[node] + while root != self._same_as[root]: + root = self._same_as[root] + while self._same_as[node] != root: + next_node = self._same_as[node] + self._same_as[node] = root + node = next_node + return root + + def _matches_anchor_filters(self, ref: str) -> bool: + from .items import compatible_relation + fact = self.edges[ref] + return (compatible_relation(fact["assertion"]["predicate"], self.query) and + (not self.query["source_scope"] or bool(self._edge_sources.get(ref, set()).intersection(self.query["source_scope"])))) + + def labels(self, sources: set[str]) -> tuple[set[str], bool, bool]: + labels: set[str] = set() + unclassified = False + # Missing proof is not an invitation to classify arbitrary nodes/decisions. + if not sources or not sources <= self._source_rows.keys(): + return labels, False, False + for source_id in sources: + row = self._source_rows[source_id] + if row["status"] in {"UNCLASSIFIED", "RETIRED"}: + unclassified = True + elif row["taxonomy_id"] == self.scope["taxonomy_id"] and row["taxonomy_hash"] == self.scope["taxonomy_hash"]: + labels.update(row["domain_ids"]) + return labels, unclassified, True + + def matches(self, sources: set[str]) -> bool: + if not self.enabled: + return True + labels, unclassified, authorized = self.labels(sources) + if not authorized: + return False + if self.scope["include_unclassified"] and unclassified: + return True + if not self._branches: + return False + if self.scope["match"] == "ANY": + return bool(labels & self.selected_domains) + # ALL with descendants means each requested branch has a matching label, + # not that a source must have every descendant label simultaneously. + for branch in self._branches: + self.work(min(len(labels), len(branch))) + if labels.isdisjoint(branch): + return False + return True + + def contributes(self, sources: set[str]) -> bool: + labels, unclassified, authorized = self.labels(sources) + return authorized and (bool(labels & self.selected_domains) or + (self.scope["include_unclassified"] and unclassified)) + + def sources_for_edges(self, refs: set[str]) -> set[str]: + return set().union(*(self._edge_sources.get(ref, set()) for ref in refs)) if refs else set() + + def node_basis(self, node: str) -> set[str]: + if node not in self._node_seed_cache: + # Only authorized same-as links propagate identity. Different-from + # remains explanatory closure, never equivalence or a domain grant. + aliases = self._equivalent_nodes.get(self._root(node), {node}) if node in self._same_as else {node} + refs = set().union(*(self._incident.get(alias, set()) for alias in aliases)) + self._node_seed_cache[node] = refs & self.contributing_edges + return self._node_seed_cache[node] + + def decision_evidence(self, ref: str) -> set[str]: + c = self.view.catalog + body = c.get(ref) + evidence = set(body.get("evidence_ids", [])) + if body.get("candidate_id") in c: + evidence.update(c.get(body["candidate_id"], "candidate")["evidence_ids"]) + return evidence + + def basis(self, kind: str, ref: str, members: list[str] | None = None) -> set[str]: + if not self.enabled: + return set() + if kind in {"EDGE", "PROVENANCE"}: + return {ref} + if kind in {"PATH", "COMMUNITY", "CONFLICT"}: + return set(members or []) & self.contributing_edges + if kind in {"NODE", "CLAIM"}: + return set(self.node_basis(ref)) + if kind == "EVIDENCE": + return self._evidence_edges.get(ref, set()) & self.contributing_edges + if kind in {"DECISION", "HYPOTHESIS"}: + return set().union(*(self._evidence_edges.get(e, set()) for e in self.decision_evidence(ref))) & self.contributing_edges + if kind in {"SCHEMA", "ONTOLOGY"}: + rule = self._relations.get(ref) + if rule is None: + return set() + types = {rule["domain"], rule["range"]} - {"*"} + basis = set() + for edge_id in self.contributing_edges: + self.work() + assertion = self.edges[edge_id]["assertion"] + if assertion["predicate"] == ref or any(self._nodes.get(assertion[key]) in types for key in ("subject", "object")): + basis.add(edge_id) + return basis + return set() + + def allows(self, kind: str, ref: str, members: list[str] | None = None) -> bool: + if not self.enabled: + return True + key = kind, ref, tuple(members or []) + if key in self._candidate_cache: + return self._candidate_cache[key] + c = self.view.catalog + permitted = False + if kind == "EVIDENCE": + if ref in self.view.available_record_ids and self.access.evidence(ref): + source_id = c.get(ref, "evidence")["source_snapshot_id"] + permitted = (not self.query["source_scope"] or source_id in self.query["source_scope"]) and self.matches({source_id}) + elif kind in {"NODE", "CLAIM"}: + if self.access.allows("node", ref) and (kind == "NODE" or ref in self.view.available_record_ids): + permitted = self.matches(self.sources_for_edges(self.node_basis(ref))) + elif kind in {"DECISION", "HYPOTHESIS"}: + if ref in self.view.available_record_ids and self.access.decision(ref): + record = c.record(ref) + record_kinds = {"candidate"} if kind == "HYPOTHESIS" else {"resolution", "evaluation", "observation"} + candidate = self.query["candidate_id"] + if record["kind"] in record_kinds and (candidate is None or + candidate not in {ref, record["body"].get("candidate_id")}): + evidence = self.decision_evidence(ref) + if all(self.access.evidence(e) for e in evidence): + permitted = self.matches({c.get(e, "evidence")["source_snapshot_id"] for e in evidence}) + elif kind in {"SCHEMA", "ONTOLOGY"}: + if self.access.allows("schema", self._schema_id): + permitted = self.matches(self.sources_for_edges(self.basis(kind, ref, members))) + elif kind in {"EDGE", "PROVENANCE", "PATH", "COMMUNITY", "CONFLICT"}: + refs = {ref} if kind in {"EDGE", "PROVENANCE"} else set(members or []) + anchors = refs & self.contributing_edges + if anchors and (anchors == refs or (kind == "CONFLICT" and refs <= self.allowed_edges.keys())): + permitted = self.matches(self.sources_for_edges(anchors)) + self._candidate_cache[key] = bool(permitted) + return bool(permitted) + + def require_candidate(self, kind: str, ref: str, members: list[str] | None = None) -> None: + require(self.allows(kind, ref, members), "RESEARCH_DOMAIN_SCOPE", "candidate is not an authorized topical anchor") + + def _unprovable_edges(self) -> set[str]: + """Edges whose transitive fact prerequisites are absent from the authorized universe.""" + state: dict[str, bool] = {} + for root in sorted(self.edges): + if root in state: + continue + stack = [(root, iter(sorted(self.edges[root]["prerequisites"])))] + state.setdefault(root, False) + while stack: + ref, parents = stack[-1] + for parent in parents: + self.work() + if parent not in self.edges: + state[ref] = True + elif parent not in state: + state[parent] = False + stack.append((parent, iter(sorted(self.edges[parent]["prerequisites"])))) + break + elif state[parent]: + state[ref] = True + else: + stack.pop() + if stack and state[ref]: + state[stack[-1][0]] = True + return {ref for ref, bad in state.items() if bad} + + def closure(self, seeds: set[str]) -> set[str]: + return self._closure(frozenset(seeds), probe=False)[0] + + def _closure(self, key: frozenset[str], *, probe: bool) -> tuple[set[str], bool]: + if (key, probe) in self._closure_cache: + return set(self._closure_cache[(key, probe)][0]), self._closure_cache[(key, probe)][1] + seeds = key + blocked = False + included: set[str] = set() + expanded: dict[str, bool] = {} + pending = deque((ref, True) for ref in sorted(seeds)) + while pending: + edge_id, expand_distinctions = 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): + continue + self.work() + require(edge_id in self.edges, "ACCESS_DENIED", "closure references an unauthorized edge") + if edge_id in self._unavailable: + require(probe, "ACCESS_DENIED", "closure requires an unauthorized or unavailable prerequisite") + blocked = True + continue + included.add(edge_id) + expanded[edge_id] = expand_distinctions + a = self.edges[edge_id]["assertion"] + parents = self.edges[edge_id]["prerequisites"] + conflicts = self._conflict_neighbors.get(edge_id, set()) + self.work(len(parents) + len(conflicts)) + for parent in sorted(parents): + pending.append((parent, True)) + for other in sorted(conflicts): + pending.append((other, expand_distinctions)) + # 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. + extend = expand_distinctions and self._identity_predicates[edge_id] != "different_from" + for node in (a["subject"], a["object"]): + equivalents = self._equivalence_incident.get(node, set()) + self.work(len(equivalents)) + for other in sorted(equivalents): + pending.append((other, extend)) + 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)) + self._closure_cache[(key, probe)] = (frozenset(included), blocked) + return included, blocked + + def item_metadata(self, source_ids: list[str], seeds: set[str], closure: set[str]) -> dict[str, Any]: + return {"version": DOMAIN_SELECTION_VERSION, "scope_hash": digest(self.scope), + "classification_hash": self.view.classification_identity["hash"], + "anchor_assertion_ids": sorted(seeds), "closure_assertion_ids": sorted(closure - seeds), + "source_assignments": {source_id: self._source_rows[source_id]["assignment_id"] for source_id in source_ids}} diff --git a/trace_gc/retrieval/integration.py b/trace_gc/retrieval/integration.py index 1e54f27..5c32b70 100644 --- a/trace_gc/retrieval/integration.py +++ b/trace_gc/retrieval/integration.py @@ -4,7 +4,7 @@ from typing import Any from ..canonical import digest from ..catalog import Catalog -from ..errors import require +from ..errors import ContractError, require LINEAGE_FIELDS = ("graph_retrieval_query_ids", "graph_context_ids", "source_retrieval_ids", "evidence_closure_id", "retrieval_fingerprint") @@ -26,6 +26,9 @@ def validate_pack_lineage(catalog: Catalog, pack: dict[str, Any], *, current_acc require(pack["materializer_version"] == "materializer-v1" and pack["packing_version"] == "complete-closure-v1", "RETRIEVAL_LINEAGE", "version claims retrieval without lineage") return + if current_access is not None: + require(current_status is not None, "SOURCE_STATUS_CAPABILITY", "live pack authorization requires current source status") + _validate_live_pack_closure(catalog, pack, current_access, current_status) require(present == set(LINEAGE_FIELDS), "RETRIEVAL_LINEAGE", "all retrieval lineage fields required") expected = lineage_fields(catalog, pack["graph_context_ids"], pack["source_retrieval_ids"], pack["closure"]["hash"]) require(all(pack[k] == expected[k] for k in LINEAGE_FIELDS), "RETRIEVAL_LINEAGE", "pack lineage differs") @@ -41,18 +44,50 @@ def validate_pack_lineage(catalog: Catalog, pack: dict[str, Any], *, current_acc require(request["requesting_component"].startswith("upstream") and request["candidate_id"] in pack["candidate_ids"], "RETRIEVAL_ROLE", "upstream candidate-bound query required") validate_context(catalog, ref, current_access=current_access, current_status=current_status) + if current_access is not None: + continue from .security import AccessFilter - policy = current_access or catalog.get(context["access_id"], "graph-access") + policy = catalog.get(context["access_id"], "graph-access") statuses = current_status if current_status is not None else context["source_status"] acl = AccessFilter(policy, catalog, statuses) for source_id in pack["closure"]["source_snapshot_ids"]: - require(acl.allows("source", source_id), "ACCESS_DENIED", "model closure source not authorized") + require(acl.source(source_id), "ACCESS_DENIED", "model closure source not currently authorized") for candidate_id in pack["candidate_ids"]: candidate = catalog.get(candidate_id, "candidate") require(acl.allows("node", candidate["assertion"]["subject"]) and acl.allows("node", candidate["assertion"]["object"]), "ACCESS_DENIED", "candidate endpoints not authorized") +def _validate_live_pack_closure(catalog: Catalog, pack: dict[str, Any], policy, statuses) -> None: + from ..adapter import validate_observation + from .security import AccessFilter + from .service import validate_context + access = AccessFilter(policy, catalog, statuses) + pending, seen = [pack], set() + while pending: + current = pending.pop() + access.require_scope(current["security_scope"]) + for ref in current["closure"]["source_snapshot_ids"]: + require(access.source(ref), "ACCESS_DENIED", "model closure source not currently authorized") + for ref in current["closure"]["record_ids"]: + record = catalog.record(ref) + if record["kind"] == "candidate": + assertion = record["body"]["assertion"] + require(all(access.allows("node", assertion[field]) for field in ("subject", "object")), + "ACCESS_DENIED", "model closure candidate endpoints not currently authorized") + for ref in current["prior_observation_ids"]: + require(access.decision(ref), "ACCESS_DENIED", "prior model observation not currently authorized") + validate_observation(catalog, ref) + prior_pack_id = catalog.get(ref, "observation")["pack_id"] + if prior_pack_id in seen: + continue + seen.add(prior_pack_id) + prior_pack = catalog.get(prior_pack_id, "pack") + for context_id in prior_pack.get("graph_context_ids", []): + validate_context(catalog, context_id, current_access=policy, current_status=statuses) + pending.append(prior_pack) + + def validate_observation_lineage(observation: dict[str, Any], pack: dict[str, Any]) -> None: require({k: observation[k] for k in LINEAGE_FIELDS if k in observation} == {k: pack[k] for k in LINEAGE_FIELDS if k in pack}, "RETRIEVAL_LINEAGE", "observation changed pack lineage") @@ -72,6 +107,41 @@ def resolution_lineage(catalog: Catalog, observations: list[str]) -> dict[str, A digest(sorted({b["retrieval_fingerprint"] for b in bodies}))} +def context_observations(context: dict[str, Any]) -> set[str]: + return {ref for item in context["items"] for ref in item["observation_ids"]} | set(context.get("reranking_observation_ids", [])) + + +def observation_uses_result(catalog: Catalog, ref: str, result_id: str, security_scope: str) -> bool: + observation = catalog.get(ref, "observation") + if observation["pack_id"] not in catalog: + return False + pack = catalog.get(observation["pack_id"], "pack") + if not (observation["security_scope"] == pack["security_scope"] == security_scope and + result_id in pack.get("source_retrieval_ids", [])): + return False + result = catalog.get(result_id, "retrieval-result") + request = catalog.get(result["query_id"], "retrieval-query") + candidate = observation["candidate_id"] + return (result["graph_context_id"] in pack["graph_context_ids"] and + request["candidate_id"] == candidate and candidate in pack["candidate_ids"]) + + +def observation_sources_readable(catalog: Catalog, ref: str, access) -> bool: + observation = catalog.get(ref, "observation") + if observation["pack_id"] not in catalog or observation["candidate_id"] not in catalog: + return False + pack = catalog.get(observation["pack_id"], "pack") + if observation["security_scope"] != access.policy["tenant"]: + return False + try: + validate_pack_lineage(catalog, pack, current_access=access.policy, current_status=access.statuses) + if "graph_context_ids" not in pack: + _validate_live_pack_closure(catalog, pack, access.policy, access.statuses) + except ContractError: + return False + return True + + def references(kind: str, body: dict[str, Any]) -> list[tuple[str, str]]: refs: list[tuple[str, str]] = [] def add(key, expected): @@ -96,8 +166,13 @@ def add(key, expected): add("query_id", "retrieval-query"); add("result_id", "retrieval-result"); add("graph_context_id", "graph-context") elif kind == "retrieval-replay": add("original_result_id", "retrieval-result"); add("replayed_result_id", "retrieval-result"); add("new_observation_ids", "observation") + add("replay_access_id", "graph-access") + if "replayed_classification_identity" in body: + refs.extend((ref, "observation") for ref in body["observation_hashes_preserved"]) elif kind == "retrieval-evaluation": add("result_ids", "retrieval-result") + if kind in {"retrieval-query", "retrieval-plan"} and body.get("research_domain_scope") is not None: + refs.append((body["research_domain_scope"]["taxonomy_id"], "research-domain-taxonomy")) if kind in {"pack", "observation", "resolution"}: add("graph_context_ids", "graph-context"); add("graph_retrieval_query_ids", "retrieval-query") add("source_retrieval_ids", "retrieval-result") @@ -109,6 +184,11 @@ def validate_record(catalog: Catalog, record: dict[str, Any]) -> None: if kind == "retrieval-query": from .contracts import validate_query validate_query(b) + from .domains import validate_scope + validate_scope(catalog, b.get("research_domain_scope")) + elif kind == "retrieval-plan": + from .domains import validate_scope + validate_scope(catalog, b.get("research_domain_scope")) elif kind == "graph-context": from .service import validate_context validate_context(catalog, record["id"]) @@ -123,6 +203,12 @@ def validate_record(catalog: Catalog, record: dict[str, Any]) -> None: context = catalog.get(b["graph_context_id"], "graph-context") require(b["graph_version"] == context["graph_version"] and b["query_id"] == context["query_id"], "RETRIEVAL_LINEAGE", "lineage query/version differs") + if b["plan_id"] is not None: + request = catalog.get(b["query_id"], "retrieval-query") + plan = catalog.get(b["plan_id"], "retrieval-plan") + require(plan["candidate_id"] == request["candidate_id"] and + digest(plan.get("research_domain_scope")) == digest(request.get("research_domain_scope")), + "RETRIEVAL_PLAN_BINDING", "candidate or research-domain scope differs") require(all(len(x) == len({row["item_id"] for row in x}) for x in (b["selected"], b["discarded"], b["candidates"])), "RETRIEVAL_LINEAGE", "duplicate selection accounting") require({r["item_id"]: r["score"] for r in b["candidates"] if r["item_id"] in context["ranking_scores"]} == context["ranking_scores"], @@ -132,6 +218,84 @@ def validate_record(catalog: Catalog, record: dict[str, Any]) -> None: candidates = {x["item_id"] for x in b["candidates"]} require(selected == {x["id"] for x in context["items"]} and not selected & discarded and selected | discarded == candidates, "RETRIEVAL_LINEAGE", "selection accounting differs") + if "classification_identity" in context: + require("research_domain_scope" in b and + digest(b.get("classification_identity")) == digest(context["classification_identity"]) and + digest(b["research_domain_scope"]) == digest(context["research_domain_scope"]), + "DOMAIN_REVISION", "lineage classification identity or scope differs") + elif kind == "retrieval-replay": + from ..adapter import validate_observation + from ..compiler import validate_pack + from ..domain_publication import classification_identity + from ..replay import RETRIEVAL_REPLAY_PARAMETERS + from .security import AccessFilter + from .service import validate_context + results = {prefix: catalog.get(b[prefix + "_result_id"], "retrieval-result") + for prefix in ("original", "replayed")} + contexts = {prefix: catalog.get(result["graph_context_id"], "graph-context") for prefix, result in results.items()} + if "replay_access_id" not in b and all("classification_identity" not in context and "research_domain_scope" not in context + for context in contexts.values()) and not any( + prefix + field in b for prefix in contexts for field in ("_classification_identity", "_research_domain_scope")): + return + require("replay_access_id" in b, "REPLAY_SCOPE", "domain-aware replay requires a bound disclosure policy") + require(set(b["changed_parameters"]) <= RETRIEVAL_REPLAY_PARAMETERS, + "REPLAY_SCOPE", "replay changes a protected query parameter") + requests = {} + for prefix, result in results.items(): + context = contexts[prefix] + request = catalog.get(result["query_id"], "retrieval-query") + requests[prefix] = request + require(result["query_id"] == context["query_id"] and + b[prefix + "_graph_version"] == context["graph_version"] and + b[prefix + "_selected_ids"] == sorted(i["id"] for i in context["items"]), + "RETRIEVAL_LINEAGE", "replay context version or selection differs") + identity_key, scope_key = prefix + "_classification_identity", prefix + "_research_domain_scope" + require(identity_key in b and scope_key in b and + digest(b[identity_key]) == digest(classification_identity(catalog.get(context["snapshot_id"], "graph-snapshot"))) and + digest(b[scope_key]) == digest(request.get("research_domain_scope")), + "DOMAIN_REVISION", "replay classification identity or scope differs") + original, replayed = contexts["original"], contexts["replayed"] + replayed_policy = catalog.get(replayed["access_id"], "graph-access") + policy = catalog.get(b["replay_access_id"], "graph-access") + require(all(policy[k] == replayed_policy[k] for k in ("tenant", "workspace", "user")), + "REPLAY_SCOPE", "replay changed the authenticated principal") + for result in results.values(): + validate_context(catalog, result["graph_context_id"], current_access=policy, current_status=replayed["source_status"]) + require(original["graph_version"] != replayed["graph_version"] or + original["snapshot_id"] == replayed["snapshot_id"], "DOMAIN_REVISION", + "the same graph version must resolve to the same snapshot") + expected = {**requests["original"], "graph_version": original["graph_version"], + "created_at": requests["replayed"]["created_at"], **b["changed_parameters"]} + require(digest(expected) == digest(requests["replayed"]), "REPLAY_SCOPE", "replayed query differs from declared changes") + old_ids, new_ids = set(b["original_selected_ids"]), set(b["replayed_selected_ids"]) + require(b["added_ids"] == sorted(new_ids - old_ids) and b["removed_ids"] == sorted(old_ids - new_ids), + "RETRIEVAL_LINEAGE", "replay selection delta differs") + preserved, new_refs = b["observation_hashes_preserved"], b["new_observation_ids"] + require(len(new_refs) == len(set(new_refs)) and not set(new_refs) & preserved.keys(), + "REPLAY_OBSERVATION_LINEAGE", "preserved and newly emitted receipts must be distinct") + comparison = b["synthesis_comparison"] + require(comparison == {"observation_ids": new_refs} or (not new_refs and comparison == { + "status": "NOT_RUN", "reason": "No synthesis executor supplied."}), + "REPLAY_OBSERVATION_LINEAGE", "comparison must be derived from authorized receipts") + original_refs = context_observations(original) + access = AccessFilter(policy, catalog, replayed["source_status"]) + for ref, value in preserved.items(): + observation = catalog.record(ref, "observation") + require(observation["hash"] == value and access.decision(ref) and observation_sources_readable(catalog, ref, access) and + (ref in original_refs or observation_uses_result( + catalog, ref, b["original_result_id"], original["security_scope"])), + "REPLAY_OBSERVATION_LINEAGE", "preserved receipt hash or original result attribution differs") + for ref in new_refs: + require(access.decision(ref) and observation_sources_readable(catalog, ref, access) and + observation_uses_result(catalog, ref, b["replayed_result_id"], replayed["security_scope"]), + "REPLAY_OBSERVATION_LINEAGE", "new receipt does not cite the replayed result") + verified_packs = set() + for ref in sorted(set(preserved) | set(new_refs)): + validate_observation(catalog, ref) + pack_id = catalog.get(ref, "observation")["pack_id"] + if pack_id not in verified_packs: + validate_pack(catalog, catalog.get(pack_id, "pack")) + verified_packs.add(pack_id) elif kind == "resolution": expected = resolution_lineage(catalog, b["observation_ids"]) require({k: b[k] for k in LINEAGE_FIELDS if k in b} == expected, "RETRIEVAL_LINEAGE", "resolver lineage differs") @@ -143,6 +307,11 @@ def validate_record(catalog: Catalog, record: dict[str, Any]) -> None: context = catalog.get(b["graph_context_id"], "graph-context") require(b["items"] == context["items"] and b["query_id"] == context["query_id"] and b["graph_version"] == context["graph_version"], "RETRIEVAL_LINEAGE", "answer context differs") + if "classification_identity" in context: + require("research_domain_scope" in b and + digest(b.get("classification_identity")) == digest(context["classification_identity"]) and + digest(b["research_domain_scope"]) == digest(context["research_domain_scope"]), + "DOMAIN_REVISION", "answer classification identity or scope differs") require(sorted(x["evidence_id"] for x in b["citations"]) == context["selected_evidence_ids"], "PROVENANCE_MISMATCH", "answer must cite every selected canonical evidence span once") for citation in b["citations"]: diff --git a/trace_gc/retrieval/items.py b/trace_gc/retrieval/items.py index 8b22193..527f0d5 100644 --- a/trace_gc/retrieval/items.py +++ b/trace_gc/retrieval/items.py @@ -1,7 +1,7 @@ """Canonical context construction and provenance classification, never graph truth.""" from __future__ import annotations from typing import Any -from ..canonical import dumps +from ..canonical import digest, dumps from ..compiler import timestamp from ..errors import require from .contracts import item_id @@ -95,22 +95,70 @@ def visible_edges(view: GraphReadView, access: AccessFilter, query: dict[str, An return result -def conflict_pairs(edges: dict[str, dict[str, Any]], relations: dict[str, Any], meter=None) -> list[list[str]]: - """Find explicit incompatible predicates, including cross-paper support/refutation.""" + +def authorized_scope_edges(view: GraphReadView, access: AccessFilter, query: dict[str, Any], meter=None) -> dict[str, Any]: + """ACL/current-status universe for domain selection and required closure. + + Relation/source filters constrain anchors, not necessary identity/refutation + proof. Unscoped requests keep their legacy filter semantics unchanged. + """ + if query.get("research_domain_scope") is None: + return visible_edges(view, access, query, meter) + closure_query = {**query, "allowed_relation_types": [], "excluded_relation_types": [], "source_scope": []} + return visible_edges(view, access, closure_query, meter) + +def conflict_pairs(edges: dict[str, dict[str, Any]], relations: dict[str, Any], meter=None, *, + resolve_identities: bool = False) -> list[list[str]]: + """Compare explicit incompatibilities inside an already authorized universe. + + The opt-in mode resolves active, authorized same-as links and the schema's + inverse/symmetric forms. It does not rewrite graph IDs or treat a domain tag + as an identity proof. The default is the original literal algorithm, retained + for old query/context pins and unscoped historical replay. + """ + from ..constraints import UnionFind, normalize + + normalized = {} + if resolve_identities: + nodes = set() + for ref, fact in edges.items(): + if meter is not None: + meter.work() + normalized[ref] = normalize(fact["assertion"], relations) + nodes.update((normalized[ref][0], normalized[ref][2])) + identities = UnionFind(nodes) + for ref, (subject, predicate, object_) in normalized.items(): + if meter is not None: + meter.work() + if predicate == "same_as" and edges[ref]["active"]: + identities.union(subject, object_) + for ref, (subject, predicate, object_) in normalized.items(): + if meter is not None: + meter.work() + if predicate not in {"same_as", "different_from"}: + subject, object_ = identities.root(subject), identities.root(object_) + if relations[predicate]["symmetric"] and subject > object_: + subject, object_ = object_, subject + normalized[ref] = (subject, predicate, object_) + else: + normalized = {ref: (fact["assertion"]["subject"], fact["assertion"]["predicate"], + fact["assertion"]["object"]) for ref, fact in edges.items()} groups: dict[str, list[str]] = {} - for ref, fact in edges.items(): - groups.setdefault(fact["assertion"]["object"], []).append(ref) + for ref, (_, _, object_) in normalized.items(): + groups.setdefault(object_, []).append(ref) result = [] for members in groups.values(): for i, left in enumerate(members): a = edges[left]["assertion"] + subject_a, predicate_a, _ = normalized[left] for right in members[i+1:]: if meter is not None: meter.work() b = edges[right]["assertion"] - opposite = b["predicate"] in relations.get(a["predicate"], {}).get("incompatible", []) or \ - a["predicate"] in relations.get(b["predicate"], {}).get("incompatible", []) - same_question = a["subject"] == b["subject"] or {a["predicate"], b["predicate"]} == {"supports", "refutes"} + subject_b, predicate_b, _ = normalized[right] + opposite = predicate_b in relations.get(predicate_a, {}).get("incompatible", []) or \ + predicate_a in relations.get(predicate_b, {}).get("incompatible", []) + same_question = subject_a == subject_b or {predicate_a, predicate_b} == {"supports", "refutes"} # Disjoint validity intervals represent change, not simultaneous conflict. qa, qb = a["qualifiers"], b["qualifiers"] disjoint = False @@ -124,14 +172,21 @@ def conflict_pairs(edges: dict[str, dict[str, Any]], relations: dict[str, Any], return sorted(result) -def canonical_item(view: GraphReadView, access: AccessFilter, query: dict[str, Any], *, kind: str, +def query_conflicts(edges: dict[str, dict[str, Any]], relations: dict[str, Any], + query: dict[str, Any], meter=None) -> list[list[str]]: + """One pinned algorithm for search, cache validation and canonical replay.""" + from .domains import identity_aware_scope + return conflict_pairs(edges, relations, meter, resolve_identities=identity_aware_scope(query)) + + +def _canonical_item(view: GraphReadView, access: AccessFilter, query: dict[str, Any], *, kind: str, ref: str, members: list[str] | None = None, edges: dict[str, Any] | None = None, conflicts: list[list[str]] | None = None) -> dict[str, Any]: """Reconstruct all source-derived text from immutable originals, not caller text.""" c, snap = view.catalog, view.snapshot edges = visible_edges(view, access, query) if edges is None else edges relations = c.get(snap["schema_id"], "schema")["relations"] - conflicts = conflict_pairs(edges, relations) if conflicts is None else conflicts + conflicts = query_conflicts(edges, relations, query) if conflicts is None else conflicts members = list(members or []) evidence_ids: set[str] = set() assertion_ids: list[str] = [] @@ -252,3 +307,90 @@ def canonical_item(view: GraphReadView, access: AccessFilter, query: dict[str, A "calibration": {"qualified": False, "note": "Retrieval status is not a calibrated truth probability."}, "generated_summary": generated, "data_origin": "GENERATED_SUMMARY" if generated else "SOURCE_DERIVED", "instruction_authority": False} + + +def _validate_scoped_topology(kind: str, ref: str, members: list[str], edges: dict[str, Any], query: dict[str, Any]) -> None: + endpoints = [] + for member in members: + assertion = edges[member]["assertion"] + endpoints.append({assertion["subject"], assertion["object"]}) + if kind == "PATH": + identity = min(members, list(reversed(members))) + require(len(members) >= 2 and ref == digest(identity), "PATH_INVALID", "path reference differs from its hops") + for start in endpoints[0]: + current, visited = start, {start} + for pair in endpoints: + following = pair - visited + if current not in pair or len(following) != 1: + break + current = following.pop() + visited.add(current) + else: + return + require(False, "PATH_INVALID", "path is not a continuous simple walk") + else: + require(members == sorted(set(members)) and ref == "community-" + digest(members)[:20], + "COMMUNITY_INVALID", "community reference differs from its members") + require(not query["community_scope"] or ref in query["community_scope"], + "COMMUNITY_SCOPE", "community is outside the requested scope") + neighbors: dict[str, set[str]] = {} + for pair in endpoints: + for node in pair: + neighbors.setdefault(node, set()).update(pair - {node}) + pending, visited = {next(iter(neighbors))}, set() + while pending: + node = pending.pop() + visited.add(node) + pending.update(neighbors[node] - visited) + require(len(visited) == len(neighbors), "COMMUNITY_INVALID", "community members are disconnected") + + +def canonical_item(view: GraphReadView, access: AccessFilter, query: dict[str, Any], *, kind: str, + ref: str, members: list[str] | None = None, edges: dict[str, Any] | None = None, + conflicts: list[list[str]] | None = None, domain_selection=None) -> dict[str, Any]: + """Canonical anchor plus atomic, authorized evidence/identity/refutation closure. + + Search paths retain their own ordered member IDs. Explanatory assertions are + separately labeled; they are never presented as extra hops in the search path. + Unscoped legacy materialization retains its original item shape and text. + """ + from .domains import ResearchDomainSelection + if query.get("research_domain_scope") is None: + return _canonical_item(view, access, query, kind=kind, ref=ref, members=members, edges=edges, conflicts=conflicts) + if domain_selection is None: + authorized = authorized_scope_edges(view, access, query) + pairs = query_conflicts(authorized, view.catalog.get(view.snapshot["schema_id"], "schema")["relations"], query) + domain_selection = ResearchDomainSelection(view, access, query, authorized, pairs) + selection = domain_selection + selection.require_candidate(kind, ref, members) + if kind in {"PATH", "COMMUNITY"}: + _validate_scoped_topology(kind, ref, members or [], selection.allowed_edges, query) + item = _canonical_item(view, access, query, kind=kind, ref=ref, members=members, + edges=selection.allowed_edges, conflicts=selection.conflicts) + seeds = selection.basis(kind, ref, members) + closure = selection.closure(seeds) + direct_assertions = set(item["assertion_ids"]) + if closure: + proof = _canonical_item(view, access, query, kind="COMMUNITY", ref=digest(sorted(closure)), members=sorted(closure), + edges=selection.edges, conflicts=selection.conflicts) + for field in ("assertion_ids", "entity_ids", "evidence_ids", "source_ids", "decision_ids", "observation_ids", + "transaction_ids", "plan_ids", "record_refs", "relation_types"): + item[field] = sorted(set(item[field]) | set(proof[field])) + item["risk_class"] = max(item["risk_class"], proof["risk_class"]) + item["provenance_complete"] = item["provenance_complete"] and proof["provenance_complete"] + if any(set(pair) <= closure for pair in selection.conflicts): + item["trust_class"] = "CONFLICTED_GRAPH_FACT" + extra = closure - direct_assertions + if extra: + item["text"] += "\nAUTHORIZED RESEARCH-DOMAIN EVIDENCE CLOSURE (not additional search-path hops): " + dumps([ + {"assertion_id": edge_id, "role": "DOMAIN_BASIS" if edge_id in seeds else "IDENTITY_OR_CONFLICT_CLOSURE", + **selection.edges[edge_id]["assertion"]} for edge_id in sorted(extra)]) + item["research_domain"] = selection.item_metadata(item["source_ids"], seeds, closure) + refs = set(item["record_refs"]) + for assignment_id in item["research_domain"]["source_assignments"].values(): + if assignment_id is not None: + refs.add(assignment_id) + refs.add(view.catalog.get(assignment_id, "classification-assignment")["taxonomy_id"]) + refs.add(selection.scope["taxonomy_id"]) + item["record_refs"] = sorted(refs) + return item diff --git a/trace_gc/retrieval/planner.py b/trace_gc/retrieval/planner.py index c1f33ff..cb73b50 100644 --- a/trace_gc/retrieval/planner.py +++ b/trace_gc/retrieval/planner.py @@ -30,7 +30,7 @@ } class RetrievalPlanner: - version = "task-risk-tier-planner-v1" + version = "task-risk-domain-tier-planner-v1" def __init__(self, policies: dict[str, list[list[str]]] | None = None, *, policy_version: str = "retrieval-routing-v1"): self.policies = deepcopy(policies or POLICIES) self.policy_version = policy_version @@ -38,11 +38,14 @@ def __init__(self, policies: dict[str, list[list[str]]] | None = None, *, policy def plan(self, catalog: Catalog, *, candidate_id: str | None, question_type: str, risk_class: str, known_entities: list[str], known_relations: list[str], budget: RetrievalBudget, - uncertainty: float | None = None, retrieval_history: list[str] | None = None, tier: int = 0) -> str: + uncertainty: float | None = None, retrieval_history: list[str] | None = None, tier: int = 0, + research_domain_scope: dict[str, Any] | None = None) -> str: require(question_type in self.policies and risk_class in {f"R{i}" for i in range(6)}, "RETRIEVAL_PLAN", "task/risk not installed") require(type(tier) is int and 0 <= tier <= 4, "RETRIEVAL_PLAN", "automatic tiers are 0..4; tier 5 is human-guided") if candidate_id: catalog.get(candidate_id, "candidate") + from .domains import validate_scope + validate_scope(catalog, research_domain_scope) methods = list(dict.fromkeys(m for layer in self.policies[question_type][:tier+1] for m in layer)) if int(risk_class[1:]) >= 4 and tier >= 1: methods = list(dict.fromkeys(methods + ["CONFLICT", "PROVENANCE"])) @@ -52,12 +55,17 @@ def plan(self, catalog: Catalog, *, candidate_id: str | None, question_type: str "known_relations": sorted(set(known_relations)), "uncertainty": uncertainty, "retrieval_history": list(retrieval_history or []), "tier": tier, "steps": [{"strategy": m, "max_hops": hop} for m in methods], "expansion_policy": "ON_UNCERTAINTY", - "budget": budget.to_dict(), "policy_version": self.policy_version, "created_at": now()}) + "budget": budget.to_dict(), "policy_version": self.policy_version, + "research_domain_scope": deepcopy(research_domain_scope), "created_at": now()}) def request(self, catalog: Catalog, plan_id: str, *, security_scope: str, text: str, retrieval_round: int, **changes: Any) -> dict[str, Any]: plan = catalog.get(plan_id, "retrieval-plan") + scope = changes.pop("research_domain_scope", plan.get("research_domain_scope")) + require(digest(scope) == digest(plan.get("research_domain_scope")), + "RETRIEVAL_PLAN_BINDING", "request changes the planned domain scope") return query(requesting_component="upstream-synthesis", security_scope=security_scope, + research_domain_scope=scope, candidate_id=plan["candidate_id"], text=text, focus_entities=plan["known_entities"], strategies=[s["strategy"] for s in plan["steps"]], budget=RetrievalBudget(**plan["budget"]), hop_limit=max((s["max_hops"] for s in plan["steps"]), default=0), @@ -142,7 +150,8 @@ def run(self, *, candidate_id: str, execute: Callable[[str], list[str]], run_bud known_entities=[candidate["assertion"]["subject"], candidate["assertion"]["object"]], known_relations=[candidate["assertion"]["predicate"]], budget=current, uncertainty=None if confidence_before is None else 1-confidence_before, - retrieval_history=results, tier=min(round_, 4)) + retrieval_history=results, tier=min(round_, 4), + research_domain_scope=(query_overrides or {}).get("research_domain_scope")) request = self.planner.request(c, plan_id, security_scope=self.retriever.access_policy["tenant"], text=c.get(candidate["claim_id"], "claim")["text"], retrieval_round=round_, **(query_overrides or {})) result_id = self.retriever.retrieve(request, plan_id=plan_id) @@ -158,13 +167,20 @@ def run(self, *, candidate_id: str, execute: Callable[[str], list[str]], run_bud result = c.get(result_id, "retrieval-result") context = c.get(result["graph_context_id"], "graph-context") task = "IDENTITY" if candidate["candidate_kind"] == "IDENTITY" else "SUPPORT" + statuses = self.retriever.validate_live_context(result["graph_context_id"]) pack_id = compile_pack(c, id_=f"graphrag-pack:{candidate_id}:{round_}:{result_id[-16:]}", run_id=candidate["run_id"], candidate_ids=[candidate_id], questions=[question(candidate_id, id_=f"semantic-{round_}", task=task)], snapshot_id=context["snapshot_id"], security_scope=self.retriever.access_policy["tenant"], execution_mode=candidate["execution_mode"], model_version=model_version, graph_context_ids=[result["graph_context_id"]], source_retrieval_ids=[result_id], - token_counter=token_counter, tokenizer_version=tokenizer_version) + token_counter=token_counter, tokenizer_version=tokenizer_version, + current_graph_access=self.retriever.access_policy, source_status=statuses) + statuses = self.retriever.validate_live_context(result["graph_context_id"]) + from .integration import validate_pack_lineage + validate_pack_lineage(c, c.get(pack_id, "pack"), current_access=self.retriever.access_policy, current_status=statuses) observations = execute(pack_id) + statuses = self.retriever.validate_live_context(result["graph_context_id"]) + validate_pack_lineage(c, c.get(pack_id, "pack"), current_access=self.retriever.access_policy, current_status=statuses) require(bool(observations) and all(c.get(x, "observation")["pack_id"] == pack_id for x in observations), "REQUEST_BINDING", "executor returned observations for a different pack") last_batch = solve(c, run_id=candidate["run_id"], candidate_ids=[candidate_id], observation_ids=observations, diff --git a/trace_gc/retrieval/reranker.py b/trace_gc/retrieval/reranker.py index 68a441a..9b2d559 100644 --- a/trace_gc/retrieval/reranker.py +++ b/trace_gc/retrieval/reranker.py @@ -29,14 +29,19 @@ def rerank(self, retriever, result_id: str, *, candidate_id: str) -> str: items = original["items"][:request["budget"]["maximum_semantic_items"]] if not items: return result_id + statuses = retriever.validate_live_context(result["graph_context_id"]) pack_id = compile_pack(c, id_="rerank-pack:" + digest([result_id, self.version, self.model_version]), run_id=candidate["run_id"], candidate_ids=[candidate_id], questions=[retrieval_question(candidate_id, i["id"], id_=f"relevance-{n}") for n, i in enumerate(items)], snapshot_id=original["snapshot_id"], security_scope=request["security_scope"], execution_mode=candidate["execution_mode"], model_version=self.model_version, program_version=RETRIEVAL_VERSION, graph_context_ids=[result["graph_context_id"]], source_retrieval_ids=[result_id], - token_counter=self.token_counter, tokenizer_version=self.tokenizer_version) + token_counter=self.token_counter, tokenizer_version=self.tokenizer_version, + current_graph_access=retriever.access_policy, source_status=statuses) started = time.monotonic() + statuses = retriever.validate_live_context(result["graph_context_id"]) + from .integration import validate_pack_lineage + validate_pack_lineage(c, c.get(pack_id, "pack"), current_access=retriever.access_policy, current_status=statuses) observation_ids = self.execute(pack_id) latency = (time.monotonic()-started)*1000 pack = c.get(pack_id, "pack") @@ -54,6 +59,8 @@ def rerank(self, retriever, result_id: str, *, candidate_id: str) -> str: bonuses[questions[obs["question_id"]]["context_item_id"]] = ( 1.0 if obs["semantic_outcome"] == "RELEVANT" else -1.0 if obs["semantic_outcome"] == "IRRELEVANT" else 0.0) require(seen == set(questions), "RERANK_OBSERVATION", "incomplete relevance judgments") + statuses = retriever.validate_live_context(result["graph_context_id"]) + validate_pack_lineage(c, pack, current_access=retriever.access_policy, current_status=statuses) context = deepcopy(original) context["ranking_scores"] = {key: value+bonuses.get(key, 0.0) for key, value in context["ranking_scores"].items()} context["items"].sort(key=lambda i: (i["kind"] != "CONFLICT", -context["ranking_scores"][i["id"]], i["id"])) @@ -81,14 +88,14 @@ def rerank(self, retriever, result_id: str, *, candidate_id: str) -> str: "warnings": sorted(set(result["warnings"]+["RELEVANCE_IS_NOT_TRUTH"])), "created_at": now()}) -def validate_reranked_context(catalog, context): +def validate_reranked_context(catalog, context, *, work_meter=None): """Rebuild a relevance-only change from the original immutable model receipts.""" from .service import validate_context require("reranking_base_context_id" in context, "RERANK_OBSERVATION", "missing original context") ref = context["reranking_base_context_id"] base = catalog.get(ref, "graph-context") require("reranking_observation_ids" not in base, "RERANK_OBSERVATION", "stacked reranking is not supported") - validate_context(catalog, ref) + validate_context(catalog, ref, work_meter=work_meter) expected = deepcopy(base) bonuses = {} pack_ids = set() diff --git a/trace_gc/retrieval/service.py b/trace_gc/retrieval/service.py index 1df35fe..f03ed99 100644 --- a/trace_gc/retrieval/service.py +++ b/trace_gc/retrieval/service.py @@ -10,10 +10,12 @@ from ..errors import ContractError, require from .budget import BudgetMeter, conservative_tokens from .contracts import RetrievalBudget, STRATEGIES, VERSION, validate_query -from .items import canonical_item, conflict_pairs, visible_edges +from .items import canonical_item, query_conflicts, authorized_scope_edges from .security import AccessFilter from .store import GraphQueryAdapter, GraphReadView 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 .vector import EmbeddingModel, HashingEmbedding, terms @@ -25,7 +27,7 @@ def __init__(self, capacity: int = 128): self.capacity = capacity self._entries: OrderedDict[str, list[dict[str, Any]]] = OrderedDict() self._lock = threading.RLock() - self.hits = self.misses = self.invalidations = 0 + self.hits = self.misses = self.invalidations = self.evictions = 0 def get(self, key: str) -> list[dict[str, Any]] | None: with self._lock: @@ -44,6 +46,7 @@ def put(self, key: str, value: list[dict[str, Any]]) -> None: self._entries.move_to_end(key) while len(self._entries) > self.capacity: self._entries.popitem(last=False) + self.evictions += 1 def invalidate(self) -> None: with self._lock: @@ -54,7 +57,7 @@ def invalidate(self) -> None: def ranking_features(item: dict[str, Any], query: dict[str, Any], similarity: float = 0.0) -> dict[str, float]: wanted = terms(query["text"]) lexical = len(wanted & terms(item["text"])) / max(1, len(wanted)) - distance = len(item["assertion_ids"]) if item["kind"] == "PATH" else 1 + distance = len(item["member_assertion_ids"]) if item["kind"] == "PATH" else 1 return {"lexical_overlap": lexical, "semantic_similarity": similarity, "entity_relevance": float(bool(set(query["focus_entities"]) & set(item["entity_ids"]))), "graph_distance_utility": 1.0 / max(1, distance), @@ -90,15 +93,18 @@ def effective_strategies(query: dict[str, Any]) -> list[str]: return sorted(dict.fromkeys(methods), key=lambda x: (x != "CONFLICT", methods.index(x))) -def retrieval_fingerprint(query, versions, embedding_version, adapter_version, acl_version): - """The precise retrieval configuration participates in qualification/replay scope.""" +def retrieval_fingerprint(query, versions, embedding_version, adapter_version, acl_version, classification=None): + """Precise retrieval scope participates in qualification and historical replay.""" methods = effective_strategies(query) - return digest({"retrieval": VERSION, "strategies": versions, "embedding": embedding_version, - "adapter": adapter_version, "ranking": query["ranking_strategy"], - "budget": query["budget"], "methods": methods, "hop_limit": query["hop_limit"], - "mode": query["mode"], "relation_filters": [query["allowed_relation_types"], query["excluded_relation_types"]], - "history": [query["include_historical"], query["include_superseded"]], - "provenance": query["include_provenance"], "acl_version": acl_version}) + body = {"retrieval": VERSION, "strategies": versions, "embedding": embedding_version, + "adapter": adapter_version, "ranking": query["ranking_strategy"], + "budget": query["budget"], "methods": methods, "hop_limit": query["hop_limit"], + "mode": query["mode"], "relation_filters": [query["allowed_relation_types"], query["excluded_relation_types"]], + "history": [query["include_historical"], query["include_superseded"]], + "provenance": query["include_provenance"], "acl_version": acl_version} + if classification is not None: + body.update(classification_identity=classification, research_domain_scope=query.get("research_domain_scope")) + return digest(body) class HybridRetriever: @@ -138,27 +144,74 @@ def retrieve(self, query: dict[str, Any], *, plan_id: str | None = None) -> str: with self._lock: return self._retrieve(deepcopy(query), plan_id=plan_id) + def _current_source_status(self, original, *, required: bool): + getter = getattr(self.adapter, "current_source_status", None) + require(callable(getter) or not required, "SOURCE_STATUS_CAPABILITY", + "domain-scoped reads require a present-status adapter hook") + return getter() if callable(getter) else original + + def _assert_current_sources(self, catalog, original, live, source_ids) -> None: + current = AccessFilter(self.access_policy, catalog, live) + for source_id in source_ids: + require(current.source(source_id), "ACCESS_DENIED", "source revoked before materialization/model use") + require(live.get(source_id) == original.get(source_id), "STALE_SOURCE_EPOCH", + "source status changed during retrieval; retry a new consistent read") + + def validate_live_context(self, context_id: str) -> dict[str, Any]: + context = self.catalog.get(context_id, "graph-context") + scoped = context.get("research_domain_scope") is not None + statuses = self._current_source_status(context["source_status"], required=scoped) + sources = {source_id for item in context["items"] for source_id in item["source_ids"]} + self._assert_current_sources(self.catalog, context["source_status"], statuses, sources) + validate_context(self.catalog, context_id, current_access=self.access_policy, current_status=statuses) + return statuses + def _retrieve(self, query: dict[str, Any], *, plan_id: str | None = None) -> str: validate_query(query) + require_live_scope(query) meter = BudgetMeter(RetrievalBudget(**query["budget"])) if self.run_budget is not None: self.run_budget.consume("retrieval_requests") view = self.adapter.read(query) + needs_status = query.get("research_domain_scope") is not None + if needs_status: + require(self._current_source_status(view.source_status, required=True) == view.source_status, + "STALE_SOURCE_EPOCH", "source status changed before domain selection; retry a consistent read") # Current source status participates in identity even for an old graph version. access = AccessFilter(self.access_policy, view.catalog, view.source_status, historical=query["include_historical"] or query["mode"] == "HISTORICAL") access.require_scope(query["security_scope"]) - for record in view.catalog.all(): - self.catalog.add(record) + validate_scope(view.catalog, query.get("research_domain_scope"), expand=False) + def current_sources(sources): + statuses = self._current_source_status(view.source_status, required=needs_status) + self._assert_current_sources(view.catalog, view.source_status, statuses, sources) + return statuses + + def embedding_sources(sources): + candidate_id = query["candidate_id"] + if candidate_id is not None and query["requesting_component"].startswith("upstream"): + candidate = self.catalog.get(candidate_id, "candidate") + assertion = candidate["assertion"] + current_access = AccessFilter(self.access_policy, view.catalog, {}) + require(all(current_access.allows("node", assertion[field]) for field in ("subject", "object")), + "ACCESS_DENIED", "embedding query candidate endpoints not authorized") + sources = sources | {self.catalog.get(ref, "evidence")["source_snapshot_id"] for ref in candidate["evidence_ids"]} + return current_sources(sources) + + if view.catalog is not self.catalog: + for record in view.catalog.all(): + self.catalog.add(record) if plan_id is not None: plan = self.catalog.get(plan_id, "retrieval-plan") - require(plan["candidate_id"] == query["candidate_id"], "RETRIEVAL_PLAN_BINDING", "candidate differs") + require(plan["candidate_id"] == query["candidate_id"] and + digest(plan.get("research_domain_scope")) == digest(query.get("research_domain_scope")), + "RETRIEVAL_PLAN_BINDING", "candidate or research-domain scope differs") query_id = self.catalog.put("retrieval-query", query) access_id = self.catalog.put("graph-access", self.access_policy) methods = effective_strategies(query) versions = {name: self.strategies[name].version for name in methods} fingerprint = retrieval_fingerprint(query, versions, self.embedding.version, - view.adapter_version, self.access_policy["version"]) + view.adapter_version, self.access_policy["version"], view.classification_identity) key_query = {k: v for k, v in query.items() if k not in {"created_at", "retrieval_round"}} key = digest({"view": view.identity, "query": key_query, "acl": access.fingerprint, "retrieval_fingerprint": fingerprint}) @@ -170,14 +223,32 @@ def _retrieve(self, query: dict[str, Any], *, plan_id: str | None = None) -> str partial = False meter.used["graph_queries"] = 1 # Consistent read, including on a cache hit. stop = "SEARCH_COMPLETE" + if candidates is not None: + try: + visible = authorized_scope_edges(view, access, query, meter) + conflicts = query_conflicts(visible, view.catalog.get(view.snapshot["schema_id"], "schema")["relations"], query, meter) + selection = ResearchDomainSelection(view, access, query, visible, conflicts, meter) + for row in candidates: + meter.check() + item = row["item"] + expected = canonical_item(view, access, query, kind=item["kind"], ref=item["canonical_ref"], + members=item["member_assertion_ids"], edges=visible, conflicts=conflicts, + domain_selection=selection) + require(item == expected, "CONTEXT_MATERIALIZATION", "cached context differs from authority") + except ContractError as exc: + if exc.code != "RETRIEVAL_BUDGET_EXHAUSTED": + raise + candidates, partial, stop = [], True, "RETRIEVAL_BUDGET_EXHAUSTED" if candidates is None: candidates_by_id: dict[str, dict[str, Any]] = {} try: meter.check() # ACL filtering precedes path expansion, embeddings and semantic models. - visible = visible_edges(view, access, query, meter) - conflicts = conflict_pairs(visible, view.catalog.get(view.snapshot["schema_id"], "schema")["relations"], meter) - space = SearchSpace(view, access, query, visible, conflicts, meter, self.embedding) + visible = authorized_scope_edges(view, access, query, meter) + conflicts = query_conflicts(visible, view.catalog.get(view.snapshot["schema_id"], "schema")["relations"], query, meter) + selection = ResearchDomainSelection(view, access, query, visible, conflicts, meter) + space = SearchSpace(view, access, query, visible, conflicts, meter, self.embedding, selection, + embedding_sources) for name in methods: meter.check() if name not in {"LEXICAL", "VECTOR", "SOURCE", "EVIDENCE"}: @@ -189,7 +260,7 @@ def _retrieve(self, query: dict[str, Any], *, plan_id: str | None = None) -> str # trust classes, provenance or access labels. canonical = canonical_item(view, access, query, kind=raw_item["kind"], ref=raw_item["canonical_ref"], members=raw_item["member_assertion_ids"], - edges=visible, conflicts=conflicts) + edges=visible, conflicts=conflicts, domain_selection=selection) require(canonical == raw_item, "CONTEXT_MATERIALIZATION", "retriever changed canonical context") features = ranking_features(canonical, query, similarity) row = candidates_by_id.setdefault(canonical["id"], {"item": canonical, "methods": [], @@ -203,8 +274,6 @@ def _retrieve(self, query: dict[str, Any], *, plan_id: str | None = None) -> str raise partial, stop = True, "RETRIEVAL_BUDGET_EXHAUSTED" candidates = list(candidates_by_id.values()) - if not partial: - self.cache.put(key, candidates) selected, discarded, rows = [], [], [] seen = {resource: set() for resource in ("nodes", "edges", "paths", "communities", "decisions", "source_spans")} ranked = sorted(candidates, key=lambda r: (r["item"]["kind"] != "CONFLICT", @@ -215,9 +284,14 @@ def _retrieve(self, query: dict[str, Any], *, plan_id: str | None = None) -> str utility = row["rrf"] if query["ranking_strategy"] == "rrf-v1" else row["score"] rows.append({"item_id": item["id"], "kind": item["kind"], "score": utility, "features": row["features"], "methods": row["methods"]}) - reported_tokens = self.token_counter(item) - require(type(reported_tokens) is int and reported_tokens >= 0, "TOKEN_ACCOUNTING", "invalid retrieval token count") - tokens = max(conservative_tokens(item), reported_tokens) + tokens = conservative_tokens(item) + if self.token_counter is not conservative_tokens: + current_sources(item["source_ids"]) + require(self.access_policy == access.policy, "ACCESS_DENIED", + "retrieval access changed before token counting; retry under current authority") + reported_tokens = self.token_counter(item) + require(type(reported_tokens) is int and reported_tokens >= 0, "TOKEN_ACCOUNTING", "invalid retrieval token count") + tokens = max(tokens, reported_tokens) if blocked_conflict_members & set(item["assertion_ids"]): accepted, reason = False, "incomplete_conflict_pair_blocked" else: @@ -237,12 +311,31 @@ def _retrieve(self, query: dict[str, Any], *, plan_id: str | None = None) -> str discarded.append({"item_id": item["id"], "reason": reason}) if discarded and stop == "SEARCH_COMPLETE": stop = "CONTEXT_BUDGET_REACHED" - selected_ids = {i["id"] for i in selected} - evidence_ids = sorted({e for i in selected for e in i["evidence_ids"]}) - source_ids = sorted({s for i in selected for s in i["source_ids"]}) + accounted_sources = {source for row in ranked for source in row["item"]["source_ids"]} + current_status = current_sources(accounted_sources) + require(self.access_policy == access.policy, "ACCESS_DENIED", + "retrieval access changed during search; retry under current authority") # Internal lineage stores only IDs needed to revalidate selected material. available = sorted({r for i in selected for r in i["record_refs"] if r in view.available_record_ids}) + if needs_status and selected: + verification_view = GraphReadView(self.catalog, view.snapshot_id, current_status, set(available), [], view.adapter_version) + verification_access = AccessFilter(self.access_policy, self.catalog, current_status) + try: + _validate_context_items(verification_view, verification_access, query, selected, meter=meter) + except ContractError as exc: + if exc.code != "RETRIEVAL_BUDGET_EXHAUSTED": + raise + discarded.extend({"item_id": i["id"], "reason": "verification_budget"} for i in selected) + selected, available = [], [] + for resource, values in seen.items(): + values.clear() + meter.used[resource] = 0 + meter.used["tokens"] = 0 + partial, stop = True, "RETRIEVAL_BUDGET_EXHAUSTED" + selected_ids = {i["id"] for i in selected} + evidence_ids = sorted({e for i in selected for e in i["evidence_ids"]}) body = {"version": VERSION, "query_id": query_id, "snapshot_id": view.snapshot_id, + "classification_identity": view.classification_identity, "research_domain_scope": query.get("research_domain_scope"), "graph_version": view.snapshot["graph_version"], "security_scope": query["security_scope"], "access_id": access_id, "source_status": {s: status for s, status in view.source_status.items() if access.allows("source", s)}, "available_record_ids": available, "focus_entities": [x for x in query["focus_entities"] if access.allows("node", x)], @@ -259,8 +352,11 @@ def _retrieve(self, query: dict[str, Any], *, plan_id: str | None = None) -> str "embedding_version": self.embedding.version, "adapter_version": view.adapter_version, "strategy_versions": versions, "created_at": now()} context_id = self.catalog.put("graph-context", body) + if not partial and not cache_hit: + self.cache.put(key, candidates) lineage = {"version": VERSION, "query_id": query_id, "graph_context_id": context_id, "plan_id": plan_id, "requesting_component": query["requesting_component"], "graph_version": body["graph_version"], + "classification_identity": view.classification_identity, "research_domain_scope": query.get("research_domain_scope"), "retrieval_strategies": methods, "strategy_versions": versions, "candidates": rows, "selected": [{"item_id": i["id"], "reason": "atomic_conflict_pair" if i["kind"] == "CONFLICT" else "bounded_utility"} for i in selected], "discarded": discarded, "budget": query["budget"], "usage": deepcopy(meter.used), @@ -272,8 +368,11 @@ def _retrieve(self, query: dict[str, Any], *, plan_id: str | None = None) -> str warnings = [stop] if partial else [] if blocked_conflict_members: warnings.append("CONFLICT_PAIR_EXCLUDED_BY_BUDGET") + if query.get("research_domain_scope") is not None and not identity_aware_scope(query): + warnings.append("LEGACY_LITERAL_CONFLICT_RESOLUTION_MAY_OMIT_ALIASED_REFUTATIONS") if not query["include_conflicts"]: - warnings.append("CONFLICT_SEARCH_DISABLED_BY_REQUEST") + warnings.append("EXPLICIT_CONFLICT_SEARCH_DISABLED_REQUIRED_CLOSURE_RETAINED" if query.get("research_domain_scope") + else "CONFLICT_SEARCH_DISABLED_BY_REQUEST") if any(i["generated_summary"] for i in selected): warnings.append("SUMMARIES_ARE_NOT_CANONICAL_EVIDENCE") if any(i["trust_class"] in {"HISTORICAL_GRAPH_FACT", "SUPERSEDED_GRAPH_FACT"} for i in selected): @@ -284,43 +383,63 @@ def _retrieve(self, query: dict[str, Any], *, plan_id: str | None = None) -> str "warnings": sorted(set(warnings)), "usage": deepcopy(meter.used), "created_at": now()}) +def _validate_context_items(view: GraphReadView, access: AccessFilter, query: dict[str, Any], items: list[dict[str, Any]], + *, meter: BudgetMeter | None = None) -> None: + if not items: + return + edges = authorized_scope_edges(view, access, query, meter) + relations = view.catalog.get(view.snapshot["schema_id"], "schema")["relations"] + conflicts = query_conflicts(edges, relations, query, meter) + selection = ResearchDomainSelection(view, access, query, edges, conflicts, meter) + for item in items: + if meter is not None: + meter.work() + expected = canonical_item(view, access, query, kind=item["kind"], ref=item["canonical_ref"], + members=item["member_assertion_ids"], edges=edges, conflicts=conflicts, + domain_selection=selection) + require(item == expected, "CONTEXT_MATERIALIZATION", "source-derived context differs from canonical records") + if meter is not None: + meter.check() + + def validate_context(catalog: Catalog, context_id: str, *, current_access: dict[str, Any] | None = None, - current_status: dict[str, Any] | None = None) -> None: + current_status: dict[str, Any] | None = None, work_meter: BudgetMeter | None = None) -> None: """Reconstruct selected data, typed projections and source attribution exactly.""" context = catalog.get(context_id, "graph-context") query = catalog.get(context["query_id"], "retrieval-query") validate_query(query) + validate_scope(catalog, query.get("research_domain_scope"), expand=False) + if work_meter is None and current_access is not None and query.get("research_domain_scope") is not None: + work_meter = BudgetMeter(RetrievalBudget(**query["budget"])) snap = catalog.get(context["snapshot_id"], "graph-snapshot") require(context["graph_version"] == snap["graph_version"] and context["security_scope"] == query["security_scope"], "STALE_GRAPH_CONTEXT", "query/snapshot/scope differs") require(query["graph_version"] is None or query["graph_version"] == snap["graph_version"], "STALE_GRAPH_CONTEXT", "explicit graph version differs") + if ("classification_identity" in context or "research_domain_scope" in context or "research_domain_scope" in query): + require(digest(context.get("classification_identity")) == digest(classification_identity(snap)) and + "research_domain_scope" in context and + digest(context["research_domain_scope"]) == digest(query.get("research_domain_scope")), + "DOMAIN_REVISION", "context taxonomy scope or classification revision differs from its exact snapshot") policy = catalog.get(context["access_id"], "graph-access") require(set(context["strategy_versions"]) == set(effective_strategies(query)) and context["retrieval_methods"] == effective_strategies(query), "RETRIEVAL_CONFIGURATION", "strategies differ") base_fingerprint = retrieval_fingerprint(query, context["strategy_versions"], context["embedding_version"], - context["adapter_version"], policy["version"]) + context["adapter_version"], policy["version"], context.get("classification_identity")) if "reranking_observation_ids" not in context: require("reranking_base_context_id" not in context and context["retrieval_fingerprint"] == base_fingerprint, "RETRIEVAL_CONFIGURATION", "retrieval fingerprint differs") else: from .reranker import validate_reranked_context - validate_reranked_context(catalog, context) + validate_reranked_context(catalog, context, work_meter=work_meter) statuses = current_status if current_status is not None else context["source_status"] access = AccessFilter(current_access or policy, catalog, statuses, historical=query["include_historical"] or query["mode"] == "HISTORICAL") access.require_scope(query["security_scope"]) view = GraphReadView(catalog, context["snapshot_id"], statuses, set(context["available_record_ids"]), [], context["adapter_version"]) - # Reconstruct conflicts using the complete authorized snapshot, including their - # sources. Persisted context statuses include selected conflicts' source spans. - edges = visible_edges(view, access, query) - conflicts = conflict_pairs(edges, catalog.get(snap["schema_id"], "schema")["relations"]) ids = [i["id"] for i in context["items"]] require(len(ids) == len(set(ids)), "DUPLICATE_ID", "context item IDs") - for item in context["items"]: - expected = canonical_item(view, access, query, kind=item["kind"], ref=item["canonical_ref"], - members=item["member_assertion_ids"], edges=edges, conflicts=conflicts) - require(item == expected, "CONTEXT_MATERIALIZATION", "source-derived context differs from canonical records") + _validate_context_items(view, access, query, context["items"], meter=work_meter) projections = {"retrieved_nodes": {e for i in context["items"] for e in i["entity_ids"]}, "retrieved_edges": {e for i in context["items"] for e in i["assertion_ids"]}, "selected_evidence_ids": {e for i in context["items"] for e in i["evidence_ids"]}, @@ -354,7 +473,7 @@ def query(self, request: dict[str, Any]) -> dict[str, Any]: c = self.retriever.catalog result = c.get(result_id, "retrieval-result") context = c.get(result["graph_context_id"], "graph-context") - validate_context(c, result["graph_context_id"], current_access=self.retriever.access_policy) + self.retriever.validate_live_context(result["graph_context_id"]) citations = [] for ref in context["selected_evidence_ids"]: evidence = c.get(ref, "evidence") @@ -365,12 +484,13 @@ def query(self, request: dict[str, Any]) -> dict[str, Any]: warnings = list(result["warnings"]) if any(i["assertion_ids"] and not i["provenance_complete"] for i in context["items"]): warnings.append("INCOMPLETE_PROVENANCE_NOT_TRUSTED_TRUTH") - if context["conflict_refs"]: + if context["conflict_refs"] or any(i["trust_class"] == "CONFLICTED_GRAPH_FACT" for i in context["items"]): warnings.append("CONFLICTING_EVIDENCE_PRESENT") if not context["items"]: warnings.append("NO_AUTHORIZED_CONTEXT") answer = {"version": VERSION, "query_id": result["query_id"], "result_id": result_id, "graph_context_id": result["graph_context_id"], "graph_version": context["graph_version"], + "classification_identity": context["classification_identity"], "research_domain_scope": context["research_domain_scope"], "mode": request["mode"], "answer_status": "CONTEXT_ONLY", "items": context["items"], "citations": citations, "warnings": sorted(set(warnings)), "can_mutate_graph": False, "created_at": now()} answer_id = c.put("graphrag-answer", answer) diff --git a/trace_gc/retrieval/strategies.py b/trace_gc/retrieval/strategies.py index 4f8ba32..1d462b3 100644 --- a/trace_gc/retrieval/strategies.py +++ b/trace_gc/retrieval/strategies.py @@ -20,11 +20,24 @@ class SearchSpace: conflicts: list[list[str]] meter: BudgetMeter embedding: EmbeddingModel + domain_selection: Any = None + source_guard: Any = None + + def __post_init__(self) -> None: + from .domains import ResearchDomainSelection + if self.domain_selection is None: + self.domain_selection = ResearchDomainSelection(self.view, self.access, self.query, self.edges, self.conflicts, self.meter) + authorized = self.domain_selection.allowed_edges + self.edges = {ref: fact for ref, fact in authorized.items() if ref in self.domain_selection.contributing_edges} + self.conflicts = [pair for pair in self.conflicts if all(ref in authorized for ref in pair)] + + def allows(self, kind: str, ref: str, members: list[str] | None = None) -> bool: + return self.domain_selection.allows(kind, ref, members) def make(self, kind: str, ref: str, members: list[str] | None = None) -> dict[str, Any]: self.meter.work(candidate=True) return canonical_item(self.view, self.access, self.query, kind=kind, ref=ref, members=members, - edges=self.edges, conflicts=self.conflicts) + edges=self.edges, conflicts=self.conflicts, domain_selection=self.domain_selection) def adjacency(self) -> dict[str, list[tuple[str, str]]]: result: dict[str, list[tuple[str, str]]] = {} @@ -42,20 +55,27 @@ def retrieve(self, space: SearchSpace) -> Iterable[dict[str, Any]]: ... class BuiltinStrategy: - version = "bounded-strategies-v1" + version = "bounded-domain-strategies-v1" def __init__(self, name: str): self.name = name def retrieve(self, space: SearchSpace) -> Iterable[dict[str, Any]]: q, c, snap, m = space.query, space.view.catalog, space.view.snapshot, space.meter + name = self.name focus = {x for x in q["focus_entities"] if space.access.allows("node", x)} + if space.domain_selection.enabled and name in {"NEIGHBORHOOD", "PATH", "COMMUNITY"}: + focus = {x for x in focus if space.domain_selection.node_basis(x)} + else: + focus = {x for x in focus if space.allows("NODE", x)} + if (space.domain_selection.enabled and q["focus_entities"] and not focus and + name in {"RELATION", "TEMPORAL", "PROVENANCE", "COMMUNITY", "CONFLICT"}): + return text_terms = terms(q["text"]) - name = self.name if name in {"ENTITY", "CLAIM"}: candidates = sorted(snap["nodes"]) if name == "ENTITY" else sorted(r["id"] for r in c.all("claim")) for ref in candidates: m.work() - if not space.access.allows("node", ref): + if not space.access.allows("node", ref) or not space.allows("NODE" if name == "ENTITY" else "CLAIM", ref): continue if ref in focus or (text_terms and text_terms & terms(ref if name == "ENTITY" else c.get(ref, "claim")["text"])): if name == "ENTITY" or ref in space.view.available_record_ids: @@ -79,12 +99,14 @@ def retrieve(self, space: SearchSpace) -> Iterable[dict[str, Any]]: next_path = path + [ref] if name == "NEIGHBORHOOD" and ref not in visited_edges: visited_edges.add(ref) - yield space.make("EDGE", ref) + if space.allows("EDGE", ref): + yield space.make("EDGE", ref) elif name == "PATH" and len(next_path) >= 2: identity = min(tuple(next_path), tuple(reversed(next_path))) if identity not in paths_seen: paths_seen.add(identity) - yield space.make("PATH", digest(list(identity)), next_path) + if space.allows("PATH", digest(list(identity)), next_path): + yield space.make("PATH", digest(list(identity)), next_path) queue.append((target, nodes+[target], next_path)) elif name in {"LEXICAL", "VECTOR", "SOURCE", "EVIDENCE"}: evidence = [] @@ -97,7 +119,7 @@ def retrieve(self, space: SearchSpace) -> Iterable[dict[str, Any]]: for r in sorted(c.all("evidence"), key=lambda r: r["id"]): m.work() ref, b = r["id"], r["body"] - if ref not in space.view.available_record_ids or not space.access.evidence(ref): + if ref not in space.view.available_record_ids or not space.access.evidence(ref) or not space.allows("EVIDENCE", ref): continue if relevant_sources and b["source_snapshot_id"] not in relevant_sources: continue @@ -115,6 +137,8 @@ def retrieve(self, space: SearchSpace) -> Iterable[dict[str, Any]]: m.work(len(evidence)) m.used["vector_queries"] += 1 # Only authorized original spans reach the injectable embedding model. + if space.source_guard is not None: + space.source_guard({c.get(ref, "evidence")["source_snapshot_id"] for ref, _ in evidence}) vectors = space.embedding.embed([q["text"]] + [text for _, text in evidence]) m.check() # Adapters must also enforce their own I/O deadline. from ..errors import require @@ -131,6 +155,8 @@ def retrieve(self, space: SearchSpace) -> Iterable[dict[str, Any]]: relations = c.get(snap["schema_id"], "schema")["relations"] for ref, rule in sorted(relations.items()): m.work() + if not space.allows("ONTOLOGY" if name == "ONTOLOGY" else "SCHEMA", ref): + continue relevant = (ref in q["focus_relationships"] or ref in q["ontology_scope"] or rule["domain"] in q["ontology_scope"] or rule["range"] in q["ontology_scope"] or (q["candidate_id"] in c and c.get(q["candidate_id"], "candidate")["assertion"]["predicate"] == ref)) @@ -155,24 +181,28 @@ def retrieve(self, space: SearchSpace) -> Iterable[dict[str, Any]]: if edge_ref not in visited and (not frontier or frontier & {a["subject"], a["object"]}): visited.add(edge_ref) following.update([a["subject"], a["object"]]) - yield space.make("EDGE", edge_ref) + if space.allows("EDGE", edge_ref): + yield space.make("EDGE", edge_ref) frontier = following if not frontier: break elif name == "CONFLICT": + authorized = space.domain_selection.allowed_edges for pair in space.conflicts: m.work() - entities = {x for ref in pair for x in (space.edges[ref]["assertion"]["subject"], space.edges[ref]["assertion"]["object"])} - if not focus or focus & entities: + entities = {x for ref in pair for x in (authorized[ref]["assertion"]["subject"], authorized[ref]["assertion"]["object"])} + if (not focus or focus & entities) and space.allows("CONFLICT", digest(pair), pair): yield space.make("CONFLICT", digest(pair), pair) for ref in pair: - yield space.make("EDGE", ref) + if space.allows("EDGE", ref): + yield space.make("EDGE", ref) elif name in {"DECISION", "SIMILAR_CASE"}: for record in sorted(c.all(), key=lambda r: r["id"]): m.work() if record["kind"] not in {"resolution", "evaluation", "observation", "candidate"} or record["id"] not in space.view.available_record_ids: continue - if not space.access.decision(record["id"]): + if not space.access.decision(record["id"]) or not space.allows( + "HYPOTHESIS" if record["kind"] == "candidate" else "DECISION", record["id"]): continue b = record["body"] if q["candidate_id"] is not None and (b.get("candidate_id") == q["candidate_id"] or record["id"] == q["candidate_id"]): @@ -194,6 +224,8 @@ def retrieve(self, space: SearchSpace) -> Iterable[dict[str, Any]]: elif name in {"RELATION", "TEMPORAL", "PROVENANCE", "GLOBAL"}: for ref, fact in space.edges.items(): m.work() + if not space.allows("PROVENANCE" if name == "PROVENANCE" else "EDGE", ref): + continue a = fact["assertion"] if q["focus_relationships"] and a["predicate"] not in q["focus_relationships"]: continue @@ -230,5 +262,5 @@ def retrieve(self, space: SearchSpace) -> Iterable[dict[str, Any]]: seen.update(nodes) if members: ref = "community-" + digest(sorted(members))[:20] - if not q["community_scope"] or ref in q["community_scope"]: + if (not q["community_scope"] or ref in q["community_scope"]) and space.allows("COMMUNITY", ref, sorted(members)): yield space.make("COMMUNITY", ref, sorted(members))