diff --git a/docs/contracts/generation-feedback-policy.md b/docs/contracts/generation-feedback-policy.md new file mode 100644 index 00000000..aea3471e --- /dev/null +++ b/docs/contracts/generation-feedback-policy.md @@ -0,0 +1,108 @@ +# Frozen generation feedback: opt-in profile + +The restricted profile accepted in +[#586](https://github.com/InferMatrixLab/InferRSI/issues/586#issuecomment-7085395676) +checks the original proof references in `CandidateContext.allowed_feedback`. +It is separate from a search/loop controller and does not grade evidence. + +## Host entry + +`inferrsi.harness.generation.prepare_generation` keeps its existing required +arguments and accepts three keyword-only options: + +| Option | Value | +| --- | --- | +| `feedback_policy_ref` | Optional existing `ArtifactRef` to canonical `CampaignPlan` v1 bytes approved by the trusted host | +| `feedback_record_refs` | Ordered sequence of existing fixed `RecordRef` values from the same authorized RunStore; empty by default | +| `artifact_reader` | Read-only `open(ArtifactRef)` port for the policy and original fixed prepared/protocol metadata | + +With no policy Ref, existing calls retain their exact preparation identity, +specification and trusted-host behavior. Feedback authorization is **host +precondition, not proved by H**. Supplying source records without a policy is +an invalid new call. + +With a policy Ref, H checks authorization before collecting context or asking +the candidate provider for a plan. A rejection at this point calls neither +provider and starts no worker. + +## Authoritative mapping + +The frozen policy has one `ScopedPrepared` per `validation_scope`. +`CampaignPlan.allowed_feedback` contains permitted **scope IDs**. +Within a permitted scope, the fixed `ProtocolV1.feedback_visibility` contains +permitted **check IDs** from its `required_evidence`. Unknown or ambiguous +bindings are refused rather than inferred. + +For each source record, H reads the requested version through its own Store, +checks the entire RecordRef, run/owner, candidate parent and captured candidate +identity, and matches its original prepared/protocol to the policy. Prepared +and protocol byte and semantic identities are verified. Identity projection +strips only schema-typed ArtifactRef locations; Parameters remain semantic. + +H resolves check IDs to actual `CheckObservation.evidence_refs`, matching the +attempt, operation, scope, checker/schema and frozen producer/control-domain +requirements. The original proof bytes must still be accessible and correct. +Every requested feedback Ref must equal one of these authorized Refs in full. +An alternate location with the same hash is not interchangeable. Whole +assessments, assessment summaries and arbitrary feedback documents are outside +this profile. + +Scopes the policy does not grant, including final-only scopes, cannot supply +feedback even if their protocol exposes checks. H uses fixed record and policy +identities, not a caller's scope label. The policy author must split or exclude +a scope used for both feedback and final-only acceptance; H cannot detect an +unexpressed mixed use. Approval of the policy itself and the contents of other +text/material channels remain trusted-host responsibilities. + +## Sealing and replay + +H retains the original policy bytes at an existing Store object address and +adds an InputSpec with role `generation_feedback_policy` and path +`inputs/generation-feedback-policy.json` to opt-in specifications. Those bytes +are frozen rule metadata, not a whole assessment. Role/path collisions are +refused after the provider's plan is available; no worker or final plan commit +follows that refusal. Object retention alone does not publish a generation +specification: the normal generation-plan seal must succeed. + +Only opt-in preparations add the original policy Ref and ordered source +RecordRefs to the preparation digest. Preserve that order and the complete +references when repreparing the same attempt. A changed Ref/sequence conflicts +with an existing delivery at `delivered-context-retention`; it cannot reuse +that delivery. Repreparation reads the already-retained policy bytes, while +the source records and required prepared/protocol/proof bytes remain subject +to fixed-reference verification. There is no fallback to `current`. +Retained-policy recovery requires a committed delivered-context row. If policy +object retention succeeded but context collection or delivery sealing failed, +repreparation still needs the original policy bytes through `artifact_reader`. + +The generation manifest has no new fields. Opt-in specs include the policy +input in the normal request digest; existing specs and descriptors are not +rewritten. This change adds no check or attempt allocation to `Harness.execute`. +With the #564 replay path, executing the same registered specification returns +the original fixed record before fresh policy/input reads, target admission or +deadline checks. Missing or corrupt retained policy bytes do not authorize a +rerun. A changed request digest still conflicts before those fresh operations. +Repreparing a generation remains a separate operation with the fixed-reference +verification described above. + +## Errors and limits + +Policy refusals use existing `PublicError` codes at `validate`: invalid input +or a missing grant uses `InvalidRequest`; unknown major versions use +`UnsupportedSchema`; unsupported matching/snapshot rules use +`UnsupportedRuleVersion`; fixed identity/producer mismatches use +`IdentityMismatch`; missing records use `RecordNotFound`; unavailable or damaged +bytes use `ArtifactUnavailable` or `ArtifactIntegrityError`. Store record damage +keeps `RecordIntegrityError`. Reader authorization errors retain their existing +code. No new verdict is introduced. + +Changed preparation identity retains `RequestConflict` at +`delivered-context-retention`. Policy retention failure uses +`ExecutionPersistenceError` at `generation-seal`, with `started=false` and no +new valid generation spec. + +H does not authenticate the person who approved the policy, scan free text for +final-only information, or add scheduling, retries or branching. A policy-role +input by itself is not an attestation that a caller used this opt-in entry. +Control records in tests are distinct from production-worker evidence; CPU +generation correctness does not establish a task or service-performance gain. diff --git a/docs/contracts/generation-feedback.md b/docs/contracts/generation-feedback.md index 696aa4d1..ec97df54 100644 --- a/docs/contracts/generation-feedback.md +++ b/docs/contracts/generation-feedback.md @@ -3,7 +3,8 @@ This documents the first-phase boundary accepted in [#371, decision 7084973960](https://github.com/InferMatrixLab/InferRSI/issues/371#issuecomment-7084973960). V25 assigns frozen feedback policy to Harness. The current -`inferrsi.harness.generation.prepare_generation` does not enforce that policy: +`inferrsi.harness.generation.prepare_generation`, when called without an explicit +`feedback_policy_ref`, does not enforce that policy: it receives a host-built `candidate_context`, retains the delivered context and seals the generation plan. There is no automatic next round on this path. @@ -16,8 +17,10 @@ acceptance results out of the next candidate context. 1. Check the permitted feedback identities and scopes against the frozen inputs. `CampaignPlan.allowed_feedback` and `ProtocolV1.feedback_visibility` contain IDs; `CandidateContext.allowed_feedback` contains concrete `ArtifactRef` values. - The host owns the mapping and authorization. H currently provides no production - port that establishes that mapping or filters an assessment for the host. + On the absent-policy path the host owns the mapping and authorization. The + separate [opt-in profile](generation-feedback-policy.md) verifies original + scope/check proof Refs when the host supplies a policy Ref and source records; + it does not filter a whole assessment for the host. 2. Supply only the approved fixed feedback bytes and references. A complete `AssessmentRef` or `AssessmentSummary` can contain other claims and scopes; permission to reveal one check does not authorize forwarding the whole result. @@ -36,20 +39,25 @@ that is separate from supplying them to the next candidate generation. Apps `CandidateProvider` checks the declared artifact closure and prepares the generation specification. H retains the bytes and commits the generation-plan -binding. Those operations establish the identity of supplied material, not that -its feedback contents were authorized by a frozen policy. Apps does not select +binding. Without the opt-in policy Ref those operations establish the identity +of supplied material, not that its feedback contents were authorized by a frozen +policy. Apps does not select feedback visibility, and B continues to own grading. -Existing function signatures and callers are unchanged. This boundary adds no -policy-reference argument, schema, automatic retry or new enforcement claim. -Policy enforcement is tracked separately in -[#586](https://github.com/InferMatrixLab/InferRSI/issues/586); its detailed reference -and scope-mapping contract must be accepted before implementation. +Existing callers without a policy Ref retain their behavior. The restricted +opt-in implementation and its accepted reference/scope-mapping contract are +tracked in [#586](https://github.com/InferMatrixLab/InferRSI/issues/586) and the +[profile contract](generation-feedback-policy.md). Policy approval, free-text +content and unexpressed mixed scope use remain trusted-host responsibilities. +Neither path adds an automatic retry, search controller or whole-assessment +feedback grant. ## Acceptance wording -The first-phase #371 acceptance record must describe this as **host precondition, +For the absent-policy path, the first-phase #371 acceptance record must describe +feedback authorization as **host precondition, not proved by H** (宿主前置责任,未由 H 证明). Tests of retained bytes, declared input closures, or a single generation cannot be reported as proof of feedback-policy enforcement. V25 remains the architectural requirement; the implementation limit -and its follow-up stay explicit until independently reviewed enforcement lands. +and its follow-up stay explicit. Opt-in acceptance must name the restricted +profile and its checks rather than claiming unrestricted V25 enforcement. diff --git a/docs/contracts/schema-and-semantics.md b/docs/contracts/schema-and-semantics.md index 0c9de2d3..127ed159 100644 --- a/docs/contracts/schema-and-semantics.md +++ b/docs/contracts/schema-and-semantics.md @@ -115,11 +115,13 @@ JSON Schema alone cannot guarantee the cross-reference, authorization, trust-sou **V25 first-phase implementation boundary:** under [#371 decision 7084973960](https://github.com/InferMatrixLab/InferRSI/issues/371#issuecomment-7084973960), feedback visibility and exclusion of final-only acceptance information are trusted-host -preconditions, not guarantees established by the current H generation-sealing port. +preconditions for generation sealing without an explicit feedback policy Ref. See the [generation feedback boundary](generation-feedback.md) for host responsibilities -and acceptance wording. Independent H enforcement is tracked in -[#586](https://github.com/InferMatrixLab/InferRSI/issues/586); V25's architectural target -is unchanged. +and acceptance wording. The restricted H opt-in profile is documented in the +[feedback policy contract](generation-feedback-policy.md) and tracked in +[#586](https://github.com/InferMatrixLab/InferRSI/issues/586); it verifies original +scope/check proof Refs without authenticating policy approval or free-text +content. V25's architectural target is unchanged. Harness commits generation inputs in append-only slots keyed by attempt and role. A retry after a generation manifest commit failure uses the same preparation request and provider configuration. Harness reuses the committed delivery, including its bytes and pins, before retrying the manifest commit. The manifest commit also binds the digest of the final execution spec in separate RunStore metadata. A changed preparation request or final spec requires a new attempt. diff --git a/docs/operations.md b/docs/operations.md index a7186fc7..3bba0de5 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -59,7 +59,8 @@ Effect classes used below: | Replay the same saved execution request | Python `inferrsi.harness.api.Harness.execute` | Existing-state query / fixed record-reading | Same attempt and canonical digest; existing state short-circuits fresh binding/execution; [replay and original limits](contracts/harness-evaluation-replay.md) | | Freeze a configured P1 preparation | Python `benchmark.preparation.PreparationService.prepare`; [production prepare](contracts/production-prepare.md) | Read-only resource access / pure encoding | Verifies supplied frozen worker/resource bytes and returns a preparation, protocol and role-keyed closure; Apps separately archives them before publishing a Ref | | Assess one fixed P1 record offline | Python `benchmark.assessment.assess`; [production assess](contracts/production-assess.md) | Read-only retained evidence / pure encoding | Verifies the frozen protocol, actual capture and proof bytes; returns independent claims without launching a worker or writing an archive; Apps selects the primary key and archives the result | -| Seal host-approved generation context | Python `harness.generation.prepare_generation`; [feedback boundary](contracts/generation-feedback.md) | Local context / generation-plan retention | The trusted host authorizes feedback and excludes final-only results before handoff. H seals the supplied material; this port does not execute a worker or prove feedback-policy enforcement | +| Seal a generation with frozen feedback authorization | Python `harness.generation.prepare_generation`; [opt-in feedback profile](contracts/generation-feedback-policy.md) | Local context / policy / generation-plan retention | Optional fixed policy and source record Refs authorize original scope/check proofs before provider calls. Absent-policy calls remain a trusted-host path; no automatic execution or policy-approval authentication | +| Seal host-approved generation context without a policy Ref | Python `harness.generation.prepare_generation`; [feedback boundary](contracts/generation-feedback.md) | Local context / generation-plan retention | The trusted host authorizes feedback and excludes final-only results before handoff. Without the opt-in policy Ref, H seals supplied material and does not prove feedback-policy enforcement or execute a worker | | Visualize a recorded run or campaign | CLI `dashboard`; [dashboard](dashboard.md) | Report-generating / local read-only serving | Writes an offline HTML snapshot or serves an optional live view on loopback; does not run an agent or validate a claim | | Capture a knowledge context | CLI `campaign capture-context`; [offline dashboard](dashboard.md#record-the-optimization-story-campaign-trace) | Local evidence-writing | Saves assembled context and resource hashes in a new `knowledge/.json`. Supports ordinary questions and explicit IDs. The only accepted explicit `--relevance-method` value is `find-lexical-v1` | | Retain an executed retrieval | Python `apps.workflows.campaign.save_retrieval`; [capture contract](knowledge-retrieval-trace.md#retain-a-standalone-result) | Local evidence-writing | Saves an existing catalog/collect result under a fresh campaign capture ID; no new search or automatic publication | diff --git a/src/inferrsi/harness/generation.py b/src/inferrsi/harness/generation.py index 3ba6142d..c8075747 100644 --- a/src/inferrsi/harness/generation.py +++ b/src/inferrsi/harness/generation.py @@ -5,7 +5,7 @@ from pathlib import PurePosixPath from inferrsi.contracts.json_v1 import encode -from inferrsi.harness import run_store +from inferrsi.harness import generation_feedback, run_store from inferrsi.harness.errors import PublicError from inferrsi.harness.execution_service import LocalCpuTarget, validate @@ -16,6 +16,7 @@ def prepare_generation( store: run_store.RunStore, target: LocalCpuTarget, *, context_provider, candidate_provider, context_request: dict, candidate_context: dict, attempt: dict, + feedback_policy_ref=None, feedback_record_refs=(), artifact_reader=None, ) -> dict: """Collect and seal the approved context, then return the final ordinary ExecutionSpec. @@ -23,6 +24,9 @@ def prepare_generation( provider configuration. A changed request requires a new attempt. The caller saves and replays this spec through Harness.execute. Preparation does not register an execution or allocate a new attempt. + With feedback_policy_ref, H verifies fixed scope/check grants before either provider + runs and retains the policy in the final spec. Without it, feedback authorization + remains a trusted-host precondition. See contracts/generation-feedback-policy.md. """ errors = run_store._attempt_errors(attempt) if errors: @@ -36,8 +40,19 @@ def prepare_generation( context.pop("delivered_context", None) preparation = {"attempt": attempt, "context_request": context_request, "candidate_context": context} + authorization = generation_feedback.request_fields( + feedback_policy_ref, feedback_record_refs, artifact_reader, + ) + preparation.update(authorization) digest = "sha256:" + sha256(encode(preparation)).hexdigest() delivery = store._find_delivery(attempt_id, preparation_digest=digest) + policy = None + if authorization: + data = generation_feedback.verify( + store, attempt, context, feedback_policy_ref, feedback_record_refs, + artifact_reader, retained=delivery is not None, + ) + policy = generation_feedback.retain(store, data, attempt_id) if delivery is None: delivery = _collect_delivery( store, context_provider, attempt_id, context_request, digest, @@ -45,7 +60,7 @@ def prepare_generation( context["delivered_context"] = delivery ref = deepcopy(delivery["artifact"]) plan = candidate_provider.plan_generation(context, deepcopy(attempt)) - spec = _bind_generation_plan(store, target, attempt, plan, ref) + spec = _bind_generation_plan(store, target, attempt, plan, ref, feedback_policy=policy) except (AttributeError, KeyError, TypeError, ValueError) as exc: raise PublicError( "InvalidRequest", stage="generation-seal", attempt_id=attempt_id, started=False, @@ -68,7 +83,7 @@ def _collect_delivery(store, context_provider, attempt_id, context_request, prep return store._seal_delivered_context(attempt_id, preparation_digest, content, descriptor) -def _bind_generation_plan(store, target, attempt, plan, delivery_ref): +def _bind_generation_plan(store, target, attempt, plan, delivery_ref, *, feedback_policy=None): attempt_id = attempt["attempt_id"] manifest = plan["manifest"] spec = deepcopy(plan["spec"]) @@ -83,6 +98,20 @@ def _bind_generation_plan(store, target, attempt, plan, delivery_ref): raise ValueError("generation plan does not match its sealed context and attempt") paths = [item["materialized_path"] for item in spec["inputs"]] paths.extend(output["path"] for step in spec["steps"] for output in step["outputs"]) + if feedback_policy is not None: + policy_path = PurePosixPath(generation_feedback.PATH) + if (any(item["role"] == generation_feedback.ROLE for item in spec["inputs"]) + or any(PurePosixPath(path.casefold()).is_relative_to(policy_path) + or policy_path.is_relative_to(PurePosixPath(path.casefold())) + for path in paths)): + raise PublicError("InvalidRequest", stage="validate", attempt_id=attempt_id, + started=False, message="generation feedback policy path is reserved") + spec["inputs"].append({ + "role": generation_feedback.ROLE, "source": feedback_policy["location"], + "source_namespace": "artifact", "source_ref": deepcopy(feedback_policy), + "snapshot_format": "file-v1", "expected_sha256": feedback_policy["sha256"], + "materialized_path": generation_feedback.PATH, + }) for source in paths: path = PurePosixPath(source.casefold()) if path.is_relative_to(_MANIFEST_PATH) or _MANIFEST_PATH.is_relative_to(path): diff --git a/src/inferrsi/harness/generation_feedback.py b/src/inferrsi/harness/generation_feedback.py new file mode 100644 index 00000000..1e1af181 --- /dev/null +++ b/src/inferrsi/harness/generation_feedback.py @@ -0,0 +1,337 @@ +"""H's opt-in, mechanical frozen-scope/check-to-retained-proof authorization. + +The host authorizes the policy Ref. This module neither grades a task nor proves +who approved that Ref, and it does not inspect free-text delivery channels. +""" + +from copy import deepcopy +from hashlib import sha256 + +from inferrsi.contracts import json_v1 +from inferrsi.harness import prepared_binding, run_store +from inferrsi.harness.errors import PublicError + +ROLE = "generation_feedback_policy" +PATH = "inputs/generation-feedback-policy.json" +_ARTIFACT = {"location", "sha256", "size_bytes", "media_type"} +_RECORD = {"attempt_id", "record_version", "artifact"} +_PREPARED_REF = {"prepared_id", "schema_version", "artifact"} +_CANDIDATE = {"candidate_id", "kind", "input_role", "parent_id", "parent_digest", "context_refs"} +_PLAN = set("schema_version campaign_id goal starting_point prepared budget_scope deadline_utc " + "advance_rule stop_rule allowed_feedback".split()) +_PROTOCOL = set("schema_version task grader operation validation_scope candidate_contract " + "worker_recipe input_requirements claim_definitions metric_definitions " + "required_evidence task_parameters baseline reference quality_reference " + "sampling feedback_visibility budget_policy_refs resources display_notes".split()) +_REQUIREMENT = set("check_id checker_revision allowed_producer_kinds subject phase artifact_schema " + "matching_rule_revision allowed_control_domains for_claims".split()) +_CHECK = set("check_id checker_revision subject phase operation validation_scope attempt_id " + "status producer evidence_refs artifact_schema reasons".split()) +_RESOURCE = {"role", "artifact", "format_schema", "required_for"} + + +def _fail(code, message): + return PublicError(code, stage="validate", started=False, message=message) + + +def _require(condition, message, code="InvalidRequest"): + if not condition: + raise _fail(code, message) + + +def _shape(value, fields): + _require(run_store._has_fields(value, fields), "invalid frozen feedback object fields") + + +def _version(value): + version = value.get("schema_version") if isinstance(value, dict) else None + if type(version) is int and version != 1: + raise _fail("UnsupportedSchema", "only frozen feedback v1 objects are supported") + _require(type(version) is int, "schema_version must be integer 1") + + +def _artifact(ref): + _shape(ref, _ARTIFACT) + _require(prepared_binding._is_path(ref["location"]) + and prepared_binding._is_sha256(ref["sha256"]) + and type(ref["size_bytes"]) is int + and 0 <= ref["size_bytes"] <= json_v1.MAX_SAFE_INTEGER + and isinstance(ref["media_type"], str) and bool(ref["media_type"]), + "invalid frozen feedback ArtifactRef") + + +def _record_ref(ref): + _shape(ref, _RECORD) + _artifact(ref["artifact"]) + _require(run_store._is_id(ref["attempt_id"]) and type(ref["record_version"]) is int + and 1 <= ref["record_version"] <= json_v1.MAX_SAFE_INTEGER, + "invalid feedback RecordRef") + + +def request_fields(policy_ref, record_refs, reader): + """Extra preparation identity only for opt-in calls; legacy has no extra keys.""" + _require(isinstance(record_refs, (tuple, list)), "feedback records must be a sequence") + if policy_ref is None: + _require(not record_refs, "feedback records require a frozen policy Ref") + return {} + _artifact(policy_ref) + _require(policy_ref["media_type"] == "application/json", "policy must be JSON") + _require(reader is not None, "policy requires an artifact reader") + for ref in record_refs: + _record_ref(ref) + _require(len({json_v1.encode(ref) for ref in record_refs}) == len(record_refs), + "feedback RecordRefs must be unique") + return {"feedback_policy_ref": deepcopy(policy_ref), + "feedback_record_refs": deepcopy(list(record_refs))} + + +def _read(reader, ref): + _artifact(ref) + try: + with reader.open(deepcopy(ref)) as stream: + parts, total, digest = [], 0, sha256() + while total <= ref["size_bytes"]: + chunk = stream.read(min(1024 * 1024, ref["size_bytes"] + 1 - total)) + if not chunk: + break + _require(isinstance(chunk, bytes), "artifact reader must supply bytes") + total += len(chunk) + digest.update(chunk) + parts.append(chunk) + except PublicError as exc: + raise _fail(exc.code, exc.message) from exc + except OSError as exc: + raise _fail("ArtifactUnavailable", "frozen feedback bytes are not accessible") from exc + _require(total == ref["size_bytes"] and digest.hexdigest() == ref["sha256"], + "frozen feedback bytes differ from their Ref", "ArtifactIntegrityError") + return b"".join(parts) + + +def _json(data): + try: + return json_v1.decode(data) + except (json_v1.CanonicalError, RecursionError) as exc: + raise _fail("ArtifactIntegrityError", "feedback metadata is not canonical JSON") from exc + + +def _resource(value): + _shape(value, _RESOURCE) + _artifact(value["artifact"]) + _require(run_store._is_id(value["role"]) + and prepared_binding._is_definition(value["format_schema"]) + and prepared_binding._is_ids(value["required_for"]), "invalid frozen resource") + return {**value, "artifact": {key: item for key, item in value["artifact"].items() + if key != "location"}} + + +def _semantic(value): + # Strip only the contract's typed ArtifactRefs, never ref-shaped Parameters. + value = deepcopy(value) + value.pop("display_notes") + if "prepared_id" in value: + value.pop("prepared_id") + value.pop("created_at") + value["protocol"].pop("location") + else: + for key in ("baseline", "reference", "quality_reference"): + if value[key] is not None: + value[key] = _resource(value[key]) + value["resources"] = [_resource(item) for item in value["resources"]] + return "sha256:" + sha256(json_v1.encode(value)).hexdigest() + + +def _candidate(value): + _shape(value, _CANDIDATE) + _require(all(run_store._is_id(value[key]) for key in ("candidate_id", "kind", "input_role")) + and (value["parent_id"] is None) == (value["parent_digest"] is None) + and (value["parent_id"] is None or (run_store._is_id(value["parent_id"]) + and prepared_binding._is_sha256(value["parent_digest"]))) + and isinstance(value["context_refs"], list), "invalid candidate identity") + for ref in value["context_refs"]: + _artifact(ref) + + +def _plan(value, context): + _version(value) + _shape(value, _PLAN) + _require(all(run_store._is_id(value[key]) for key in ("campaign_id", "budget_scope")) + and isinstance(value["goal"], str) and run_store._is_timestamp(value["deadline_utc"]) + and all(prepared_binding._is_definition(value[key]) + for key in ("advance_rule", "stop_rule")), "invalid CampaignPlan") + _require(value["campaign_id"] == context.get("campaign_id"), + "policy belongs to another campaign", "IdentityMismatch") + _shape(value["starting_point"], {"candidate", "inputs", "generation_record_ref"}) + _candidate(value["starting_point"]["candidate"]) + from inferrsi.harness.execution_service import _input_errors + + _require(not _input_errors(value["starting_point"]["inputs"]), "invalid starting inputs") + _require(sum(item["role"] == value["starting_point"]["candidate"]["input_role"] + for item in value["starting_point"]["inputs"]) == 1, + "starting candidate needs one input role") + if value["starting_point"]["generation_record_ref"] is not None: + _record_ref(value["starting_point"]["generation_record_ref"]) + _require(isinstance(value["prepared"], list) and value["prepared"], "missing policy scopes") + scoped = {} + for item in value["prepared"]: + _shape(item, {"validation_scope", "prepared_ref", "protocol_digest"}) + scope, ref = item["validation_scope"], item["prepared_ref"] + _require(run_store._is_id(scope) and scope not in scoped, "ambiguous policy scope") + _version(ref) + _shape(ref, _PREPARED_REF) + _artifact(ref["artifact"]) + _require(prepared_binding._is_semantic_id(ref["prepared_id"]) + and prepared_binding._is_semantic_id(item["protocol_digest"]), + "invalid scoped preparation identity") + scoped[scope] = item + _require(prepared_binding._is_ids(value["allowed_feedback"]) + and set(value["allowed_feedback"]) <= scoped.keys(), "invalid granted scopes") + return scoped + + +def _requirements(reader, scoped): + ref = scoped["prepared_ref"] + data = _read(reader, ref["artifact"]) + try: + fixed = prepared_binding.project(data) + except PublicError as exc: + code = "InvalidRequest" if exc.code == "InvalidExecutionSpec" else exc.code + raise _fail(code, exc.message) from exc + prepared = _json(data) + _require((fixed.prepared_id, fixed.protocol_digest, fixed.validation_scope) == ( + ref["prepared_id"], scoped["protocol_digest"], scoped["validation_scope"]), + "scoped preparation binding differs", "IdentityMismatch") + _require(_semantic(prepared) == fixed.prepared_id, + "prepared semantic identity differs", "ArtifactIntegrityError") + protocol = _json(_read(reader, prepared["protocol"])) + _version(protocol) + _shape(protocol, _PROTOCOL) + _require(_semantic(protocol) == fixed.protocol_digest, + "protocol semantic identity differs", "ArtifactIntegrityError") + _require(all(prepared[key] == protocol[key] for key in ( + "task", "grader", "operation", "validation_scope", "candidate_contract", + "required_evidence")) and prepared["recipe"] == protocol["worker_recipe"], + "prepared and protocol fields differ", "IdentityMismatch") + requirements = {} + _require(isinstance(protocol["required_evidence"], list), "invalid evidence requirements") + for item in protocol["required_evidence"]: + _shape(item, _REQUIREMENT) + key = item["check_id"] + _require(run_store._is_id(key) and key not in requirements, "ambiguous evidence check") + _require(all(run_store._is_id(item[field]) for field in ( + "checker_revision", "matching_rule_revision", "subject", "phase", + )) and prepared_binding._is_ids(item["for_claims"]), "invalid evidence rule identity") + _require(item["matching_rule_revision"] == "1", "unsupported evidence matching rule", + "UnsupportedRuleVersion") + _require(prepared_binding._is_ids(item["allowed_producer_kinds"]) + and prepared_binding._is_ids(item["allowed_control_domains"]) + and prepared_binding._is_definition(item["artifact_schema"]), + "invalid evidence authorization") + requirements[key] = item + visible = protocol["feedback_visibility"] + _require(prepared_binding._is_ids(visible), "invalid visible check IDs") + _require(set(visible) <= requirements.keys(), "unknown visible check ID", + "UnsupportedRuleVersion") + return fixed, {key: requirements[key] for key in visible} + + +def verify(store, attempt, context, policy_ref, record_refs, reader, *, retained=False): + try: + return _verify(store, attempt, context, policy_ref, record_refs, reader, retained=retained) + except (AttributeError, KeyError, TypeError, ValueError, RecursionError) as exc: + raise _fail("InvalidRequest", "invalid frozen feedback metadata") from exc + + +def _verify(store, attempt, context, policy_ref, record_refs, reader, *, retained): + """Validate opt-in inputs before any provider call; return original policy bytes.""" + source = {**policy_ref, "location": run_store.object_location( + store.namespace, policy_ref["sha256"], + )} if retained else policy_ref + data = _read(store if retained else reader, source) + policy = _json(data) + scoped = _plan(policy, context) + wanted = context.get("allowed_feedback") + _require(isinstance(wanted, list), "feedback must be an ArtifactRef list") + for ref in wanted: + _artifact(ref) + _require(len({json_v1.encode(ref) for ref in wanted}) == len(wanted), "duplicate feedback Ref") + parent = context.get("parent") + if record_refs: + _candidate(parent) + approved, candidate_digest = set(), None + for ref in record_refs: + _require(ref["attempt_id"] != attempt["attempt_id"], "feedback reuses generation attempt", + "IdentityMismatch") + try: + committed = store.committed(ref["attempt_id"], ref["record_version"]) + except PublicError as exc: + raise _fail(exc.code, exc.message) from exc + record = committed.payload + _require(committed.record_ref == ref and record["run_id"] == attempt["run_id"] + and record["owner"] == attempt["owner"] and record["candidate"] == parent, + "feedback record/parent/run/owner differs", "IdentityMismatch") + scope = record["validation_scope"] + _require(scope in policy["allowed_feedback"], "feedback scope is not granted") + item = scoped[scope] + _require(record["prepared_ref"] == item["prepared_ref"] + and record["protocol_digest"] == item["protocol_digest"], + "record does not match policy preparation", "IdentityMismatch") + fixed, visible = _requirements(reader, item) + _require(record["operation"] == fixed.operation + and parent["kind"] == fixed.candidate_kind + and parent["input_role"] == fixed.candidate_input_role, + "record operation differs", "IdentityMismatch") + bound = [value for value in record["bound_inputs"] + if value["role"] == parent["input_role"]] + _require(len(bound) == 1 and bound[0]["actual_sha256"] is not None + and bound[0]["retained_ref"] is not None, "parent input is unavailable", + "ArtifactUnavailable") + _require(bound[0]["snapshot_format"] == "file-v1", "unsupported parent snapshot format", + "UnsupportedRuleVersion") + _require(bound[0]["attempt_id"] == record["attempt_id"], + "parent input belongs to another attempt", "IdentityMismatch") + _read(store, bound[0]["retained_ref"]) + actual = bound[0]["actual_sha256"] + _require(actual == bound[0]["retained_ref"]["sha256"] + and (candidate_digest is None or candidate_digest == actual), + "parent captured identity differs", "IdentityMismatch") + candidate_digest = actual + if context.get("candidate") is not None: + _candidate(context["candidate"]) + _require((context["candidate"]["parent_id"], context["candidate"]["parent_digest"]) + == (parent["candidate_id"], actual), "next candidate parent differs", + "IdentityMismatch") + for check in record["checks"]: + _require(run_store._has_fields(check, _CHECK), "invalid fixed check fields", + "RecordIntegrityError") + requirement = visible.get(check["check_id"]) + if requirement is None: + continue + producer = check["producer"] + _require(run_store._has_fields(producer, { + "kind", "identity", "revision", "control_domain", "capture_route", + }), "invalid fixed producer fields", "RecordIntegrityError") + _require(all(check[key] == requirement[key] for key in ( + "check_id", "checker_revision", "subject", "phase", "artifact_schema")) + and check["attempt_id"] == record["attempt_id"] + and check["operation"] == record["operation"] + and check["validation_scope"] == scope + and producer["kind"] in requirement["allowed_producer_kinds"] + and producer["control_domain"] in requirement["allowed_control_domains"], + "feedback evidence producer/binding differs", "IdentityMismatch") + for artifact in check["evidence_refs"]: + _read(store, artifact) + approved.add(json_v1.encode(artifact)) + _require(all(json_v1.encode(ref) in approved for ref in wanted), + "feedback Ref is not an approved original check proof") + return data + + +def retain(store, data, attempt_id): + ref = run_store.artifact_ref(store.namespace, data, "application/json") + try: + store._retain(ref, data) + except (OSError, run_store._StorageFault, run_store._IntegrityFault) as exc: + raise PublicError("ExecutionPersistenceError", stage="generation-seal", + attempt_id=attempt_id, started=False, + message="feedback policy retention failed") from exc + return ref diff --git a/tests/test_harness_feedback_policy.py b/tests/test_harness_feedback_policy.py new file mode 100644 index 00000000..713d5af7 --- /dev/null +++ b/tests/test_harness_feedback_policy.py @@ -0,0 +1,423 @@ +"""Frozen feedback authorization controls, distinct from production-worker evidence.""" + +import io +import sqlite3 +import subprocess +import sys +from copy import deepcopy +from hashlib import sha256 +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from inferrsi.contracts.json_v1 import decode, encode +from inferrsi.harness import run_store +from inferrsi.harness.errors import PublicError +from inferrsi.harness.generation import prepare_generation +from tests.test_apps_generation_plan import _fixed_input, _provider +from tests.test_apps_generation_plan import generation as generation +from tests.test_harness_generation_seal import cpu_generation as cpu_generation + +FIXTURES = Path(__file__).resolve().parents[1] / "docs/contracts/fixtures/t108-v4" + + +class Reader: + def __init__(self, values): + self.values = values + + def open(self, ref): + if ref["location"] not in self.values: + raise PublicError("ArtifactUnavailable", stage="open", message="control bytes absent") + return io.BytesIO(self.values[ref["location"]]) + + +def document(reader, location, value): + data = encode(value) + reader.values[location] = data + return {"location": location, "sha256": sha256(data).hexdigest(), + "size_bytes": len(data), "media_type": "application/json"} + + +@pytest.fixture +def authorized(cpu_generation, generation, request): + store, target, harness, draft, inputs = cpu_generation + control = getattr(request, "param", None) + original = decode((FIXTURES / "execution-spec.json").read_bytes()) + attempt = {key: deepcopy(original[key]) for key in inputs["attempt"]} + for key in ("run_id", "owner", "deadline_utc", "resources", "budget", "target_request"): + attempt[key] = deepcopy(inputs["attempt"][key]) + if control == "owner": + attempt["owner"] = "another-owner" + spec = {**original, **attempt} + payload = decode((FIXTURES / "record-payload.json").read_bytes()) + for key in attempt.keys() & payload.keys(): + payload[key] = deepcopy(attempt[key]) + payload["request_digest"] = run_store.request_digest(spec) + prepared = decode((FIXTURES / "prepared.json").read_bytes()) + protocol_bytes, prepared_bytes = ((FIXTURES / name).read_bytes() + for name in ("protocol.json", "prepared.json")) + if control in ("matching-rule", "protocol-version", "semantic"): + # Pure fixture identity calculations; no production prepare/worker claim. + from inferrsi.benchmark import preparation + + protocol = decode(protocol_bytes) + if control == "matching-rule": + protocol["required_evidence"][0]["matching_rule_revision"] = "2" + prepared["required_evidence"] = deepcopy(protocol["required_evidence"]) + elif control == "protocol-version": + protocol["schema_version"] = 2 + else: + protocol["task_parameters"]["label"] += " changed semantic parameter" + if control != "semantic": + prepared["protocol_digest"] = preparation.protocol_digest(protocol) + protocol_bytes = encode(protocol) + prepared["protocol"].update(sha256=sha256(protocol_bytes).hexdigest(), + size_bytes=len(protocol_bytes)) + prepared["prepared_id"] = preparation.prepared_id(prepared) + prepared_bytes = encode(prepared) + payload["protocol_digest"] = prepared["protocol_digest"] + payload["prepared_ref"].update(prepared_id=prepared["prepared_id"]) + payload["prepared_ref"]["artifact"].update(sha256=sha256(prepared_bytes).hexdigest(), + size_bytes=len(prepared_bytes)) + candidate_bytes = (FIXTURES / "candidate.txt").read_bytes() + candidate = run_store.artifact_ref(store.namespace, candidate_bytes, "application/octet-stream") + # This is an explicitly controlled proof, not output from a production task worker. + proof_bytes = encode({"control": "format-check", "candidate_sha256": candidate["sha256"]}) + proof = run_store.artifact_ref(store.namespace, proof_bytes, "application/json") + payload["bound_inputs"] = [{ + "role": "candidate", "retained_ref": candidate, "actual_sha256": candidate["sha256"], + "snapshot_format": "file-v1", "captured_at": payload["recorded_at"], + "attempt_id": attempt["attempt_id"], "step_ids": [payload["steps"][0]["step_id"]], + "materialized_path": "inputs/candidate", "expected_sha256": candidate["sha256"], + "identity_status": "matched", "reasons": [], + }] + if control == "snapshot": + payload["bound_inputs"][0]["snapshot_format"] = "unknown-v2" + check = deepcopy(payload["checks"][0]) + check.update(check_id="format", status="passed", reasons=[], evidence_refs=[proof], + artifact_schema={"name": "format-proof", "revision": "1"}) + if control == "producer": + check["producer"]["kind"] = "task_worker" + payload["checks"] = [check] + payload["budget_admission"]["scope_id"] = attempt["budget"]["scope_id"] + with store.claim(attempt, payload["request_digest"]) as claim: + record = claim.commit(payload, [(candidate, candidate_bytes), (proof, proof_bytes)]) + context = inputs["candidate_context"] + context.update(parent=deepcopy(payload["candidate"]), allowed_feedback=[proof]) + + def bind(candidate_context): + return [_fixed_input("knowledge", candidate_context["delivered_context"]["artifact"]), + *[_fixed_input(f"feedback-{index}", ref) + for index, ref in enumerate(candidate_context["allowed_feedback"])]] + + inputs["candidate_provider"] = _provider(generation, bind) + reader = Reader({prepared["protocol"]["location"]: protocol_bytes, + payload["prepared_ref"]["artifact"]["location"]: prepared_bytes}) + policy = { + "schema_version": 1, "campaign_id": context["campaign_id"], "goal": "software control", + "starting_point": {"candidate": payload["candidate"], + "inputs": [_fixed_input("candidate", candidate)], + "generation_record_ref": None}, + "prepared": [{"validation_scope": payload["validation_scope"], + "prepared_ref": payload["prepared_ref"], + "protocol_digest": payload["protocol_digest"]}], + "budget_scope": attempt["budget"]["scope_id"], "deadline_utc": attempt["deadline_utc"], + "advance_rule": {"name": "manual-control", "revision": "1"}, + "stop_rule": {"name": "manual-stop", "revision": "1"}, + "allowed_feedback": [payload["validation_scope"]], + } + ref = document(reader, "policies/feedback.json", policy) + return store, target, harness, inputs, reader, ref, policy, record, proof_bytes + + +def test_control_record_has_original_retained_proof(authorized): + store, _, _, _, _, _, _, record, data = authorized + assert record.payload["started"] is False # Not called a production worker result. + with store.open(record.payload["checks"][0]["evidence_refs"][0]) as stream: + assert stream.read() == data + + +def prepare(case, **overrides): + store, target, _, inputs, reader, ref, _, record, _ = case + options = {"feedback_policy_ref": ref, "feedback_record_refs": [record.record_ref], + "artifact_reader": reader, **overrides} + return prepare_generation(store, target, **inputs, **options) + + +def test_opt_in_retains_policy_and_allowed_proof_for_real_generation(authorized): + store, _, harness, inputs, reader, ref, _, _, proof_bytes = authorized + spec = prepare(authorized) + policy_input = next(item for item in spec["inputs"] + if item["role"] == "generation_feedback_policy") + with store.open(policy_input["source_ref"]) as stream: + assert stream.read() == reader.values[ref["location"]] + del reader.values[ref["location"]] # The original policy archive is no longer needed. + result = harness.execute(spec) + assert result["exit_code"] == 0 + bound = next(item for item in result["bound_inputs"] if item["role"] == "feedback-0") + with store.open(bound["retained_ref"]) as stream: + assert stream.read() == proof_bytes + assert prepare(authorized) == spec + assert result["attempt_id"] == inputs["attempt"]["attempt_id"] + + +@pytest.mark.parametrize("fault", ["missing", "corrupt"]) +def test_registered_policy_generation_replays_before_fresh_authorization( + authorized, monkeypatch, tmp_path, fault, +): + from inferrsi.harness import execution_service, generation_feedback + from inferrsi.harness.api import Harness, LocalCpuTarget + + store, _, harness, _, _, _, _, _, _ = authorized + spec = prepare(authorized) + saved = encode(spec) + original = harness.execute(decode(saved)) + assert original["exit_code"] == 0 + before = store.committed(original["attempt_id"]) + policy = next(item["source_ref"] for item in spec["inputs"] + if item["role"] == "generation_feedback_policy") + path = store.root / "objects" / policy["sha256"][:2] / policy["sha256"] + assert path.resolve().is_relative_to(tmp_path.resolve()) + data = path.read_bytes() + if fault == "missing": + path.unlink() + else: + path.write_bytes(bytes([data[0] ^ 1]) + data[1:]) + + def forbidden(*args, **kwargs): + pytest.fail("registered generation performed fresh authorization or execution") + + class Never: + open = forbidden + + monkeypatch.setattr(generation_feedback, "verify", forbidden) + monkeypatch.setattr(execution_service, "_budget", forbidden) + monkeypatch.setattr(execution_service, "_deadline_seconds", forbidden) + monkeypatch.setattr(execution_service.local_process, "_supervise", forbidden) + monkeypatch.setattr(store, "claim", forbidden) + monkeypatch.setattr(run_store.Claim, "commit", forbidden) + monkeypatch.setattr(run_store, "utc_now", lambda: "2100-01-01T00:00:00Z") + retired = Harness(store, LocalCpuTarget("retired", "2", tmp_path / "retired"), + artifact_reader=Never()) + replayed = retired.execute(decode(saved)) + assert replayed["record_ref"] == original["record_ref"] + assert replayed["request_digest"] == original["request_digest"] + changed = decode(saved) + changed["deadline_utc"] = "2098-01-01T00:00:00Z" + with pytest.raises(PublicError) as caught: + retired.execute(changed) + assert (caught.value.code, caught.value.stage) == ("RequestConflict", "claim") + assert store.committed(original["attempt_id"]).payload_bytes == before.payload_bytes + assert encode(spec) == saved + with store._connection() as connection: + assert connection.execute("SELECT count(*) FROM attempts").fetchone()[0] == 2 + assert connection.execute("SELECT count(*) FROM records").fetchone()[0] == 2 + + +@pytest.mark.parametrize("fault,code", [ + ("denied-scope", "InvalidRequest"), ("extra-ref", "InvalidRequest"), + ("unknown-version", "UnsupportedSchema"), ("wrong-scope", "InvalidRequest"), + ("wrong-parent", "IdentityMismatch"), ("bad-hash", "ArtifactIntegrityError"), + ("absent", "ArtifactUnavailable"), + ("alternate-ref", "InvalidRequest"), ("assessment", "InvalidRequest"), + ("bad-proof", "ArtifactIntegrityError"), ("absent-proof", "ArtifactUnavailable"), + ("bad-candidate", "ArtifactIntegrityError"), ("unknown-ref-version", "UnsupportedSchema"), + ("bool-version", "InvalidRequest"), ("ambiguous", "InvalidRequest"), + ("bad-binding", "IdentityMismatch"), +]) +def test_refusal_precedes_both_providers(authorized, fault, code): + store, target, _, inputs, reader, ref, policy, record, _ = authorized + if fault == "denied-scope": + policy["allowed_feedback"] = [] + elif fault == "unknown-version": + policy["schema_version"] = 2 + elif fault == "wrong-scope": + policy["prepared"][0]["validation_scope"] = "development" + policy["allowed_feedback"] = ["development"] + elif fault == "extra-ref": + inputs["candidate_context"]["allowed_feedback"].append( + {**ref, "location": "unapproved/whole-assessment.json"}) + elif fault == "wrong-parent": + inputs["candidate_context"]["parent"]["candidate_id"] = "another-parent" + elif fault == "alternate-ref": + inputs["candidate_context"]["allowed_feedback"][0] = { + **inputs["candidate_context"]["allowed_feedback"][0], "location": "other/same-bytes", + } + elif fault == "assessment": + inputs["candidate_context"]["allowed_feedback"] = [document( + reader, "fixtures/whole-assessment.json", + decode((FIXTURES / "assessment.json").read_bytes()), + )] + elif fault in ("bad-proof", "absent-proof", "bad-candidate"): + artifact = (record.payload["bound_inputs"][0]["retained_ref"] if fault == "bad-candidate" + else record.payload["checks"][0]["evidence_refs"][0]) + path = store.root / "objects" / artifact["sha256"][:2] / artifact["sha256"] + assert path.resolve().is_relative_to(store.root.resolve()) + if fault == "absent-proof": + path.unlink() + else: + path.write_bytes(b"controlled corruption\n") + elif fault == "unknown-ref-version": + policy["prepared"][0]["prepared_ref"]["schema_version"] = 2 + elif fault == "bool-version": + policy["schema_version"] = True + elif fault == "ambiguous": + policy["prepared"].append(deepcopy(policy["prepared"][0])) + elif fault == "bad-binding": + policy["prepared"][0]["prepared_ref"]["prepared_id"] = "sha256:" + "0" * 64 + if fault not in ("bad-hash", "absent"): + ref = document(reader, ref["location"], policy) + elif fault == "bad-hash": + reader.values[ref["location"]] = b"changed bytes\n" + else: + del reader.values[ref["location"]] + + def forbidden(*args, **kwargs): + raise AssertionError("refused feedback reached a provider") + + with pytest.raises(PublicError) as error: + prepare_generation( + store, target, **{**inputs, + "context_provider": SimpleNamespace(collect=forbidden), + "candidate_provider": SimpleNamespace(plan_generation=forbidden)}, + feedback_policy_ref=ref, feedback_record_refs=[record.record_ref], + artifact_reader=reader, + ) + assert (error.value.code, error.value.stage) == (code, "validate") + with sqlite3.connect(store.root / "index.sqlite3") as connection: + assert connection.execute("SELECT count(*) FROM generation_inputs").fetchone()[0] == 0 + + +@pytest.mark.parametrize("changed", ["policy", "records"]) +def test_changed_authorization_does_not_replay_an_old_delivery(authorized, changed): + prepare(authorized) + _, _, _, _, reader, ref, _, _, _ = authorized + if changed == "policy": + alternate = {**ref, "location": "policies/other.json"} + reader.values[alternate["location"]] = reader.values[ref["location"]] + override = {"feedback_policy_ref": alternate} + else: + override = {"feedback_record_refs": []} + with pytest.raises(PublicError) as error: + prepare(authorized, **override) + assert (error.value.code, error.value.stage) == ("RequestConflict", + "delivered-context-retention") + + +def test_absent_policy_keeps_the_exact_legacy_preparation_identity(cpu_generation): + store, target, _, _, inputs = cpu_generation + spec = prepare_generation(store, target, **inputs) + assert prepare_generation(store, target, **inputs, feedback_policy_ref=None) == spec + context = deepcopy(inputs["candidate_context"]) + context.pop("delivered_context", None) + expected = "sha256:" + sha256(encode({ + "attempt": inputs["attempt"], "context_request": inputs["context_request"], + "candidate_context": context, + })).hexdigest() + with sqlite3.connect(store.root / "index.sqlite3") as connection: + metadata = connection.execute( + "SELECT descriptor FROM generation_inputs WHERE role='delivered-context'", + ).fetchone()[0] + assert decode(metadata)["preparation_digest"] == expected + assert all(item["role"] != "generation_feedback_policy" for item in spec["inputs"]) + + +@pytest.mark.parametrize("authorized,code", [ + ("owner", "IdentityMismatch"), ("producer", "IdentityMismatch"), + ("matching-rule", "UnsupportedRuleVersion"), ("protocol-version", "UnsupportedSchema"), + ("semantic", "ArtifactIntegrityError"), ("snapshot", "UnsupportedRuleVersion"), +], indirect=["authorized"]) +def test_record_and_protocol_controls_fail_closed(authorized, code): + def forbidden(*args, **kwargs): + raise AssertionError("invalid source metadata reached a provider") + + authorized[3].update(context_provider=SimpleNamespace(collect=forbidden), + candidate_provider=SimpleNamespace(plan_generation=forbidden)) + with pytest.raises(PublicError) as error: + prepare(authorized) + assert (error.value.code, error.value.stage) == (code, "validate") + + +def test_policy_retention_failure_never_calls_providers(authorized, monkeypatch): + store, target, _, inputs, reader, ref, _, record, _ = authorized + + def forbidden(*args, **kwargs): + raise AssertionError("policy retention failure reached a provider") + + def fail(*args, **kwargs): + raise OSError("controlled policy retention failure") + + monkeypatch.setattr(store, "_retain", fail) + with pytest.raises(PublicError) as error: + prepare_generation( + store, target, **{**inputs, + "context_provider": SimpleNamespace(collect=forbidden), + "candidate_provider": SimpleNamespace(plan_generation=forbidden)}, + feedback_policy_ref=ref, feedback_record_refs=[record.record_ref], + artifact_reader=reader, + ) + assert (error.value.code, error.value.stage, error.value.started) == ( + "ExecutionPersistenceError", "generation-seal", False, + ) + with sqlite3.connect(store.root / "index.sqlite3") as connection: + assert connection.execute("SELECT count(*) FROM generation_inputs").fetchone()[0] == 0 + + +def test_authorization_imports_no_other_business_module_in_a_child(authorized, tmp_path): + store, _, _, inputs, reader, ref, _, record, _ = authorized + bundle = {"root": str(store.root), "namespace": store.namespace, + "attempt": inputs["attempt"], "context": inputs["candidate_context"], + "policy": ref, "records": [record.record_ref], + "resources": {name: data.decode("utf-8") for name, data in reader.values.items()}} + path = tmp_path / "authorization.json" + path.write_bytes(encode(bundle)) + child = """ +import io, json, sys +sys.path.insert(0, sys.argv[1]) +from inferrsi.harness.generation_feedback import verify +from inferrsi.harness.run_store import RunStoreReader +data = json.load(open(sys.argv[2], encoding='utf-8')) +class Reader: + def open(self, ref): + return io.BytesIO(data['resources'][ref['location']].encode('utf-8')) +store = RunStoreReader(data['root'], data['namespace']) +verify(store, data['attempt'], data['context'], data['policy'], data['records'], Reader()) +assert not any(name.startswith(('inferrsi.apps', 'inferrsi.benchmark', 'inferrsi.knowledge')) + for name in sys.modules) +""" + result = subprocess.run( + [sys.executable, "-I", "-B", "-c", child, + str(Path(__file__).resolve().parents[1] / "src"), str(path)], + cwd=tmp_path, capture_output=True, text=True, encoding="utf-8", timeout=30, + ) + assert result.returncode == 0, result.stderr + + +@pytest.mark.parametrize("collision", ["role", "path", "casefold-prefix"]) +def test_opt_in_policy_role_and_path_are_reserved(authorized, collision): + store, _, _, inputs, _, _, _, _, _ = authorized + provider = inputs["candidate_provider"] + + def plan(context, attempt): + value = provider.plan_generation(context, attempt) + extra = _fixed_input("another-input", context["delivered_context"]["artifact"]) + if collision == "role": + extra["role"] = "generation_feedback_policy" + else: + extra["materialized_path"] = ("inputs/generation-feedback-policy.json" + if collision == "path" else + "inputs/GENERATION-FEEDBACK-POLICY.JSON/child") + value["spec"]["inputs"].append(extra) + return value + + inputs["candidate_provider"] = SimpleNamespace(plan_generation=plan) + with pytest.raises(PublicError) as error: + prepare(authorized) + assert (error.value.code, error.value.stage) == ("InvalidRequest", "validate") + # Collision detection needs the provider's plan; no execution/plan commit follows. + with sqlite3.connect(store.root / "index.sqlite3") as connection: + assert connection.execute("SELECT count(*) FROM attempts").fetchone()[0] == 1 + assert connection.execute( + "SELECT count(*) FROM generation_inputs WHERE role='generation-plan'", + ).fetchone()[0] == 0