Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions docs/contracts/generation-feedback-policy.md
Original file line number Diff line number Diff line change
@@ -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.
32 changes: 20 additions & 12 deletions docs/contracts/generation-feedback.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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.
Expand All @@ -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.
10 changes: 6 additions & 4 deletions docs/contracts/schema-and-semantics.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
3 changes: 2 additions & 1 deletion docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<id>.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 |
Expand Down
35 changes: 32 additions & 3 deletions src/inferrsi/harness/generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -16,13 +16,17 @@
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.

A retry with the same preparation request uses the committed delivery and the same
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:
Expand All @@ -36,16 +40,27 @@ 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,
)
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,
Expand All @@ -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"])
Expand All @@ -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):
Expand Down
Loading
Loading